I'm using the Spring Form library to handle a search page in my application. Here is a snipped from my DD showing the bean configuration:
<bean name="/search.html" class="myapp.web.AccountSearchController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="searchAccounts"/>
<property name="commandClass" value="myapp.service.AccountSearch"/>
<property name="validator">
<bean class="myapp.service.AccountSearchValidator"/>
</property>
<property name="formView" value="accountSearch"/>
<property name="successView" value="accountSearch"/>
</bean>
The validator class is quite simple:
package myapp.service;
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class AccountSearchValidator implements Validator {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public boolean supports(Class clazz) {
return AccountSearch.class.equals(clazz);
}
public void validate(Object obj, Errors errors) {
AccountSearch accountSearch = (AccountSearch) obj;
if (accountSearch == null) {
errors.rejectValue("domainName", "error.accountSearch.neither-specified", null, "Value required.");
} else if (accountSearch.getAccountId().isEmpty() &&
accountSearch.getDomainName().isEmpty() ) {
errors.rejectValue("domainName", "error.accountSearch.neither-specified", null, "Value required.");
}
}
}
In my JSP, my form is displayed in an HTML table. I want field specific errors to be displayed under the respective field as a separate table row. Here's a snippet:
<tr>
<td align="right" valign="top"><form:label path="domainName">Domain Name</form:label>:</td>
<td><form:input path="domainName" size="30"/></td>
</tr>
<tr>
<td> </td>
<td><form:errors path="domainName" cssClass="error"/></td>
</tr>
The question I have is - how can I make the output of the error row conditional on the existence of the error? Is the Validator instance accessible from my JSP? What would the test be for a c:if tag?
Thanks,
-aj
OK it took me a few days but I figured it out:
<c:set var="domainNameErrors"><form:errors path="domainName"/></c:set>
<c:if test="${not empty domainNameErrors}">
<tr>
<td> </td>
<td>${domainNameErrors}</td>
</tr>
</c:if>
This article was very helpful: http://forum.springsource.org/archive/index.php/t-51044.html
Use <spring:hasBindErrors name="loginPasswordForm">
Use <spring:bind path="fieldName">
and check status.error
to see if the field has error
Example
<spring:bind path="phoneNumber">
<form:input path="phoneNumber" />
<form:errors path="phoneNumber" cssClass="error" />
${status.error ? 'has error' : ''}
</spring:bind>
Note
<form:input path="" />
must be inside <spring:bind >
tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With