Inject custom validation errors in object

18 / Aug / 2011 by Uday Pratap Singh 2 comments

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

[java]
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"
}
})
}
}
[/java]

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

[java]
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’)
}
}
[/java]

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

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Bert

    Hello there, You’ve done an incredible job. I’ll definitely digg it and personally recommend to my friends.
    I’m confident they will be benefited from
    this web site.
    Website: Drivelan Ultra prezzo in farmacia

    Reply
  2. Kenneth Sirmon

    Hey, you used to write wonderful, but the last few posts have been kinda boring… I miss your tremendous writings. Past several posts are just a little out of track! come on!

    Reply

Leave a Reply

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