12.5 Validation and Internationalization 6.0.0

(Quick Reference) # 12.5 Validation and Internationalization Version: 6.0.0 ## 12.5 Validation and Internationalization Another important thing to note about errors in Grails is that error messages are not hard coded anywhere. The FieldError class in Spring resolves messages from message bundles using Grails' i18n support. #### Constraints and Message Codes The codes themselves are dictated by a convention. For example consider the constraints we looked at earlier:
    package com.mycompany.myapp

    class User {
        ...

        static constraints = {
            login size: 5..15, blank: false, unique: true
            password size: 5..15, blank: false
            email email: true, blank: false
            age min: 18
        }
    }
If a constraint is violated, Grails looks by convention for a message code:
Constraint | Error Code
--- | ---
blank | `className.propertyName.blank`
creditCard | `className.propertyName.creditCard.invalid`
email | `className.propertyName.email.invalid`
inList | `className.propertyName.not.inList`
matches | `className.propertyName.matches.invalid`
max | `className.propertyName.max.exceeded`
maxSize | `className.propertyName.maxSize.exceeded`
min | `className.propertyName.min.notmet`
minSize | `className.propertyName.minSize.notmet`
notEqual | `className.propertyName.notEqual`
nullable | `className.propertyName.nullable`
range | `className.propertyName.range.toosmall` or `className.propertyName.range.toobig`
size | `className.propertyName.size.toosmall` or `className.propertyName.size.toobig`
unique | `className.propertyName.unique`
url | `className.propertyName.url.invalid`
validator | `classname.propertyName.` + String returned by Closure
In the case of the `blank` constraint this would be `user.login.blank` so you would need a message such as the following in your `grails-app/i18n/messages.properties` file:
    user.login.blank=Your login name must be specified!
The class name is looked for both with and without a package, with the packaged version taking precedence. So for example, `com.mycompany.myapp.User.login.blank` will be used before `user.login.blank`. This allows for cases where your domain class message codes clash with a plugin’s. For a reference on what codes are for which constraints refer to the reference guide for each constraint (e.g. blank). #### Displaying Messages The renderErrors tag will automatically look up messages for you using the message tag. If you need more control of rendering you can handle this yourself:
    <g:hasErrors bean="${user}">
      <ul>
       <g:eachError var="err" bean="${user}">
           <li><g:message error="${err}" /></li>
       </g:eachError>
      </ul>
    </g:hasErrors>
In this example within the body of the eachError tag we use the message tag in combination with its `error` argument to read the message for the given error. | Quick Reference (hide)