12.4 Validation on the Client

Displaying Errors

Typically if you get a validation error you redirect back to the view for rendering. Once there you need some way of displaying errors. Grails supports a rich set of tags for dealing with errors. To render the errors as a list you can use renderErrors:

  1. <g:renderErrors bean="${user}" />

If you need more control you can use hasErrors and eachError:

  1. <g:hasErrors bean="${user}">
  2. <ul>
  3. <g:eachError var="err" bean="${user}">
  4. <li>${err}</li>
  5. </g:eachError>
  6. </ul>
  7. </g:hasErrors>

Highlighting Errors

It is often useful to highlight using a red box or some indicator when a field has been incorrectly input. This can also be done with the hasErrors by invoking it as a method. For example:

  1. <div class='value ${hasErrors(bean:user,field:'login','errors')}'>
  2. <input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>
  3. </div>

This code checks if the login field of the user bean has any errors and if so it adds an errors CSS class to the div, allowing you to use CSS rules to highlight the div.

Retrieving Input Values

Each error is actually an instance of the FieldError class in Spring, which retains the original input value within it. This is useful as you can use the error object to restore the value input by the user using the fieldValue tag:

  1. <input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>

This code will check for an existing FieldError in the User bean and if there is obtain the originally input value for the login field.