It just takes 15 seconds. Send your
details and we’ll get back to you soon.

Inject custom validation errors in object

Reading the grails docs is like my habit, they always enhances your learning. Today I was going through the grails docs again and I found a very good way of showing some custom error messages. As I saw it I found the use case in one of my project that could be refactored by this approach

There are use cases where we need to show some errors which are beyond your domain / command object constraints validators for these cases you can inject your custom error messages to the object take an example of updating the password. Any of the field is not domain related so we have to create a command object like

class UpdatePasswordCO {

    String password
    String newPassword
    String confirmNewPassword

    static constraints = {
        password(nullable: false, blank: false)
        newPassword(nullable: false, blank: false)
        confirmNewPassword(nullable: false, blank: false, validator: {val,   obj ->
            if (obj.newPassword != val) {
                "confirmPassword.mismatch.newPassword"
            }
        })
    }
}

Now you have to check whether the logged in user entered the correct password or not. So rather than putting the message in flash scope you can directly put this error to the command object it self

def updatePassword = {UpdatePasswordCO updatePasswordCO ->
        if (updatePasswordCO.validate()) {
            if (User.loggedInUser.validatePassword(updatePasswordCO.password)) {
                flash.message = "Password updated successfully"
            } else {
                updatePasswordCO.errors.rejectValue("password", "password.mismatch.current.password")
            }
        }
        if (updatePasswordCO.hasErrors()) {
            render(view: 'profile', model: [updatePasswordCO: updatePasswordCO])
        } else {
            redirect(action: 'profile')
        }
}

So in above approach you have injected a new error on password field with a code. By doing this your hasErrors tag on gsp page will show your custom error as well. For more details you can refer Spring

Hope it helps
Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap
http://in.linkedin.com/in/meudaypratap

 

Hope it helps
Uday Pratap Singh
uday@intelligrape.com
http://in.linkedin.com/in/meudaypratap

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>