Reputation: 38390
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?
Upvotes: 16
Views: 13750
Reputation: 9634
I use the Grails Fields plugin to do this, and it works a treat.
It makes it easy to create default templates for form field rendering. For example I have the following in grails-app/views/_fields/default/_field.gsp
:
<%@ page defaultCodec="html" %>
<div class="control-group${invalid ? ' error' : ''}">
<label class="control-label" for="${property}${index ?: ""}">${label}</label>
<div class="controls">
<%= widget.replace("id=\"${property}\"", "id=\"${property}${index ?: ""}\"") %>
<g:if test="${invalid}"><span class="help-inline">${errors.join('<br>')}</span></g:if>
</div>
</div>
As you can see from the HTML the errors are displayed inline. Here is part of my login form:
<g:form controller="home" action="login" >
<f:field bean="user" property="email"/>
<f:field bean="user" property="password">
<g:field type="password" name="${property}" value="${value}"/>
</f:field>
</g:form>
Upvotes: 7
Reputation: 493
Here is the custom error in context, wrapped around username field. This will do what you want.
<dt>User Id</dt>
<dd><g:textField name="username" value="${user?.username}"/>
<g:hasErrors bean="${user}" field="username">
<g:eachError bean="${user}" field="username">
<p style="color: red;"><g:message error="${it}"/></p>
</g:eachError>
</g:hasErrors>
</dd>
Upvotes: 4
Reputation: 35864
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.
Upvotes: 12
Reputation: 10848
I would recommend going with Jquery validation plugin. There's several Grails plugin about this, but they are a bit out-dated. Besides, I think this task is pretty simple for using another plugin.
Upvotes: 1