Grails Error Messages Custom Validators
Contents |
12Validation 13The Service Layer 14Static Type Checking And Compilation 15Testing 16Internationalization 17Security 18Plugins 19Grails and Spring 20Grails and Hibernate 21Scaffolding 22Deployment 23Contributing to Grails Quick Reference See the light - agile, industrial strength, rapid web application development made grails custom validator example easy (Quick Reference) validatorPurposeAdds custom validation to a field.Examples// Simple validator appending an grails validation messages 'invalid' error to the error object even validator: { return (it % 2) == 0 }// is equivalent to even grails custom error messages validator: { val -> return (val % 2) == 0 }// Closure with two arguments, the second being the object itself password1 validator: { val, obj -> obj.password2 == val }// Closure with three
Grails Validation Error Messages
arguments, the third being the errors object password1 validator: { val, obj, errors -> if (!(obj.password2 == val)) errors.rejectValue('password1', 'noMatch') }// Examples that pass arguments to the error message in message.properties// Example 1: Using the "implicit" argument 0 (property name)class Person { String name static constraints = { name validator: { if (!it) return ['entryMissing'] } }// This maps to a message // person.name.entryMissing=Please enter a name grails form validation example in the field {0}// Example 2: Using the "implicit" arguments 0 (property name) and 2 (property value)class Person { Integer yearOfBirth static constraints = { yearOfBirth validator: { if (yearOfBirth>2013) return ['yearTooBig'] } }// This maps to a message // person.name.entryMissing=The value {2} entered in the field {0} is not valid because it lies in the future. // You will note when using this kind of message on Integers that years are displayed as 1,990 instead of 1990. // This is addressed in the next example.// Example 3: Much more complexclass Astronaut { Integer yearOfBirth Integer yearOfFirstSpaceTravel yearOfFirstSpaceTravel validator: { val, obj -> if (val < obj.yearOfBirth) ['datePriorTo', val.toString(), obj.yearOfBirth] else if (val < (obj.yearOfBirth+18)) ['maybeABitTooYoung', val-obj.yearOfBirth] } }// Respective messages // Note that argument 3 is the property value converted toString to avoid the unwanted formatting as described before. astronaut.yearOfFirstSpaceTravel.datePriorTo=The value {3} entered for the year of the first space travel is prior to the year of birth ({4}). Please correct the value. astronaut.yearOfFirstSpaceTravel.maybeABitTooYoung={3} years seems a bit young for travelling to space, dude!DescriptionA custom validator is implemented by a Closure that takes up to three parameters. If the Closure accepts zero or one parameter, the parameter v
Spring 15Grails and Hibernate 16Scaffolding 17Deployment 18Contributing to Grails Quick Reference See the light - agile, industrial strength, rapid web application development made easy (Quick Reference) validatorPurposeAdds custom validation to a field.Exampleseven grails rejectvalue validator: { return (it % 2) == 0 }password1 validator: { val,
Grails Custom Constraints
obj -> obj.password2 == val }magicNumber validator: someClosureWithTwoParameters// This one assumes you have an error message defined like //
Grails @validateable
this (wrapped here only for display purposes): // classname.propertyName.custom.error= My error shows arguments {3} and {4} for value {0} otherProperty validator: { return ['custom.error', arg1, arg2] }// The following example http://docs.grails.org/3.1.1/ref/Constraints/validator.html does not use custom validation. // A custom message may be defined in messages.properties: // user.username.blank=Please enter a username // which will be used instead of default.blank.message class User { String username static constraints = { username blank: false } }// In the following example, custom validation is used: // user.username.validator.invalid=Please enter a username class User { String username static http://docs.grails.org/2.0.0/ref/Constraints/validator.html constraints = { username validator: { return it.length != 0 } } }// The following might define the error message as: // user.username.invalid.bountyhunter=Invalid bounty hunter ({2}) tried to log in. class User { String username static constraints = { username validator: { if (!it.startsWith('boba')) return ['invalid.bountyhunter'] } } }DescriptionA custom validator is implemented by a Closure that takes up to three parameters. If the Closure accepts zero or one parameter, the parameter value will be the one being validated ("it" in the case of a zero-parameter Closure). If it accepts two parameters the first is the value and the second is the domain class instance being validated. This is useful when your validation needs access to other fields, for example when checking that two entered passwords are the same. If it accepts three parameters the first is the value, the second is the instance, and the third is the Spring Errors object.The closure can return: null or true (or no return value) to indicate that the value is valid false to indicate an invalid value and use the default m
not excellent documentation. I am working on a business project where I am using Grails REST services with MongoDB as the backend. I will http://javawithravi.com/custom-validation-message-in-grails/ cover that setup in another blog post but this one is for providing information about setting up validation in Grails with custom validation messages. Some background about Domain objects in Grails: Often we have requirements where certain fields in the request need to have certain values. In other words, we need to validate the data in the incoming request. Grails provides error messages constraints2 on domain and validatable3 objects. Below is an example. package com.javawithravi.bookstore class Book { String title String description static constraints = { title nullable: false, blank: false, size: 10..50 description nullable: false, blank: false, size: 100..500 } } For example: #9 above states that title cannot be: 1. empty 2. null or 3. less than 10 chars or more than 50 grails error messages chars in length. One line and you are done with constraints on title property. No need to write custom validation logic (not that you can't write custom constraint in Grails but you are provided with some common constraints out of the box). Default messages for constraint violation: Now, Grails comes with default messages.properties that provides default validation message(s) for each of the in-built constraints. A few examples: default.invalid.min.message=Property [{0}] of class [{1}] with value [{2}] is less than minimum value [{3}] default.invalid.max.size.message=Property [{0}] of class [{1}] with value [{2}] exceeds the maximum size of [{3}] default.invalid.min.size.message=Property [{0}] of class [{1}] with value [{2}] is less than the minimum size of [{3}] So if you provide a title less than 10 chars long then you will get a message like: Property [title] of class [com.javawithravi.bookstore.Book] with value [Yo] is less than the minimum size of [10] Custom constraint message: Pretty decent. But not very user friendly. So here's the good news. You can provide your own custom message for each domain class's constraint(s). To quote Grails doc: If a constraint is violated Grails wil