Validation Basics
To validate a domain class you can call the
validate method on any instance:
def user = new User(params)if(user.validate()) {
// do something with user
}
else {
user.errors.allErrors.each {
println it
}
}
The
errors
property on domain classes is an instance of the Spring
Errors interface. The
Errors
interface provides methods to navigate the validation errors and also retrieve the original values.
Validation Phases
Within Grails there are essentially 2 phases of validation, the first phase is
data binding which occurs when you bind request parameters onto an instance such as:
def user = new User(params)
At this point you may already have errors in the
errors
property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the
Errors
API:
if(user.hasErrors()) {
if(user.errors.hasFieldErrors("login")) {
println user.errors.getFieldError("login").rejectedValue
}
}
The second phase of validation happens when you call
validate or
save. This is when Grails will validate the bound values againts the
constraints you defined. For example, by default the persistent
save method calls
validate
before executing hence allowing you to write code like:
if(user.save()) {
return user
}
else {
user.errors.allErrors.each {
println it
}
}