Grails - Validation on the Client



Description

It displays the errors, if you get errors on validating the client side and redirect back to view for rendering. Grails provides different types of tags for associating with errors and use the renderErrors tag for displaying the list of errors.

<g:renderErrors bean="${team}" as="list" field="name"/>

The above format contains below attributes:

  • as: It is an optional attribute which displays the options as list and xml. The default option is list.

  • bean: It is an optional attribute which is used for checking errors with the bean name.

  • field: It is an optional attribute which is used for checking errors within bean or model.

Displaying Errors

You can check for any other errors in bean, request scope or model by using the hasErrors tag and loop through the bean or model for checking errors by using the eachError tag.

<g:hasErrors bean="${team}">
  <ul>
   <g:eachError var="teamerr" bean="${team}">
       <li>${teamerr}</li>
   </g:eachError>
  </ul>
</g:hasErrors>

The errors can be highlighted using some red color or indicator, when a field contains incorrect input. This can be determined by invoking the hasErrors tag as a method.

<div class='value ${hasErrors(bean:team,field:'fname','errors')}'>
   <input type="text" name="fname" value="${fieldValue(bean:team,field:'fname')}"/>
</div>

In the above code, if there are any errors for the fname field of the team bean, then it will add an errors CSS class to the div to highlight the div.

The input value can be retrieved by using the fieldValue tag as shown below:

<input type="text" name="fname" value="${fieldValue(bean:team,field:'fname')}"/>
Advertisements