In Grails, how do I display validation error messages next to the fields?

Daniel T. picture Daniel T. · Jun 8, 2012 · Viewed 13.4k times · Source

The Grails 2.0.4 documentation for validation shows you how to display error messages at the top of the page and how to add a css class to an element if a field is invalid, but it doesn't tell you how to display the error message next to the fields themselves, something like this:

      -----------------------
Name: |                     |  You must enter a name!
      -----------------------

How do you retrieve the specific error message for an invalid field and then display it next to the field it's for?

Answer

Gregg picture Gregg · Jun 8, 2012

Actually, the documentation does show how to do this, it just isn't overly clear that this is what they mean:

<g:renderErrors bean="${book}" as="list" field="title"/>

If you specify the field attribute, it will only render error(s) for that field. So then it is just up to you to write the HTML accordingly.

<input type="text" ... /> <g:if test="${bean.hasErrors}"><g:renderErrors bean="${book}" as="list" field="title"/></g:if>

It can get as simple or as complicated as you would like it and while I generally like grails plugins, this just seems simple enough to do without one and you have more control over the markup.