This tutorial is about Custom Validation. The tutorial includes an introduction to Validation, limitation to built-in validators, the validator closure parameter, the validator closure return value and custom error message. The tutorial begins with a section which gives an introduction to Validation. It answers the question to as to what is validation and also includes examples to explain validation in brief.
Followed by is a limitation section. It talks about the limitation to built-in validators with a few examples like password validator, custom error message and also includes using a custom validator. Then comes the closure parameter section. It includes the validator closure parameters like one parameter closure, two parameter closure and three parameter closure.
The next section is on closure return value. It gives a brief explanation on validator closure return value like null for valid, false for invalid, a list containing a string and then any number of arguments following it. The last section of the tutorial is about custom error message. It includes a brief about the definition of custom error message, the following arguments that are passed automatically and an example to explain it in brief.
3. What is validation ?
● Business rules that constrain the valid values of a particular property in a
domain class
● Forexample
- A Person must never have an age that islessthan zero
- Rules like these should be expressed clearly, and in only one place
4. Limitation to built-in validators
Itisimpossible to foresee every feasibledomain
model and every specific kind of validation that
an application might need
5. Limitation to built-in validators Cont...
• Forexample, Let'sconsider the case withPassword validator:
− should be minimum of specified length
− should not contain any field from personal information(name, email, date
of birth, contactno. etc)
− should use mix of alphabets, digits and special characters( a-z A-Z0-9
$#@^&*)
− confirm password fieldmust match
6. Limitation to built-in validators Cont...
• Customerrormessagedepending ontheinvalid data entered.
− Password must be 8 characters long
− Password should not containyour name
− confirm password do not match
− Weak password, use digits andspecial characters.
7. Example 1 (Built-in Validator)
class Employee{
String name
static constraint ={
name(blank:false)
}
}
8. Using Custom Validator
class Employee{
String name
static constraint ={
Name(
validator:{
//closure with one,two or three parameter
//return value determines thevalidation
//null or true to indicate that the value isvalid
// false to indicate an invalid value
}
)
}
}
9. Validator Closure parameter
• A single or no parameter block receives the value
• A two-parameter block receives the value and object reference
• A three-parameter Closure receives the value, object reference and the
errorsobject
10. One Parameter Closure
class User{
Stringlogin
static constraints ={
login(validator: {
// itcontains new value for login field
println propertyName
if (!it.startsWith('boba'))
return['invalid.bountyhunter']
})
}
}
11. Two Parameter Closure
class User {
String login
Stringpassword
static constraints ={
password(validator: {newValue, obj ->
println newValue
println obj.class.name
println obj.properties['login']
if
(obj.properties['login'].contains(newValue
))
return 'Error:Password contains login name'
})
}
}
12. Three Parameter Closure
class User {
String login
Stringpassword
static constraints ={
password(validator: {newValue, obj,err
->
printlnnewValue
//entered value for password
println obj.class.name //User
println obj.properties['login'] //entered value
forlogin
printlnerr
if
(obj.properties['login'].contains(newValue
))
return 'Error:Password contains login name'
})
}
}
13. Validator Closure return value
• Null or true to indicate that the value isvalid
• False to indicate an invalid value and use the default
message code
14. Validator Closure return value Cont...
• A string to indicate the error code to append to the
"classname.propertName." string used to resolve the error message. Ifa
field specific message cannot be resolved, the error code itself will be
resolved allowing for global error messages
• A listcontaining a string as above, and then any number of arguments
following it, which can be used as formatted message arguments
indexed at 3 onwards. See grails-app/i18n/message.properties to see
how the default error message codes use the arguments
15. Custom Error Message
• Error messages can bedefined in grails-app/i18n/message.properties
file in the following format :
errorcode=error message
• e.g.
custom.error=Error occured, property={0} class= {1}value= {2}arg1={3}
• Now you can return any of these error code whose corresponding error
message wil be rendered on views(<g:hasError....tag)
16. Custom Error Message Cont...
• Inerror messages you can use the following arguments that are passed
automatically:
−{0}for propertyName e.g. Login
− {1}forDomain class name e.g. class Employee
− {2}forvalue entered for the validation field
− {3}for 1st argument you pass along with errorcode
−{4}for 2nd argument you pass with errorcode
And soon
17. Example with Custom Error
class User {
String userId
String password
Stringpassword2
static transients =['password2']
static constraints ={
password(blank: false, nullable: false,size:5..20, validator:
{password, obj->
def password2 =obj.properties['password2']
if(password2 ==null) return true /*skip matching password
validation(only important when setting/resetting pass) */
password2 ==password ? true :
['invalid.matchingpasswords']
})
}
}
18. Contact us
Our Office
Client
Location
Click Here To Know More!
Have more queries on Grails?
Talk to our GRAILS experts
Now!
Talk To Our Experts
Here's how the world's
biggest Grails team is
building enterprise
applications on Grails!