Displaying Errors
Typically if you get a validation error you want to redirect back to the view for rendering. Once there you need some way of rendering errors. Grails supports a rich set of tags for dealing with errors. If you simply want to render the errors as a list you can use
renderErrors:
<g:renderErrors bean="${user}" />
If you need more control you can use
hasErrors and
eachError:
<g:hasErrors bean="${user}">
<ul>
<g:eachError var="err" bean="${user}">
<li>${err}</li>
</g:eachError>
</ul>
</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:
<div class='value ${hasErrors(bean:user,field:'login','errors')}'>
<input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>
</div>
What this code does is check if the
login
field of the
user
bean has any errors and if it does adds an
errors
CSS class to the
div
thus 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:
<input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>
This code will look if there is an existing
FieldError
in the
User
bean and if there is obtain the originally input value for the
login
field.