I have a simple Spring 3 MVC form using jsp taglibs. I need to add a class based on whether a field within the form has any errors associated with it or not. Here is a snipet
While this is a little more obscure I think it's simpler because it's a single line which is what it would be if I were just using scriplets like any sane Java dev should. Taglibs need to die die die die, then die some more. They are horrible and I can't believe Java devs still think they actually help and not waste our utter time. PHP developers laugh at us when we use those things.
<div class="control-group ${requestScope['org.springframework.validation.BindingResult.user'].hasFieldErrors('firstName') ? 'error' : ''}">
There is a better way to get the error message
<spring:hasBindErrors name="yourCommandName">
${errors.hasFieldErrors('userId') ? errors.getFieldError('userId').defaultMessage : ''}
</spring:hasBindErrors>
And one liner
${requestScope['org.springframework.validation.BindingResult.user'].hasFieldErrors('emailId') ? requestScope['org.springframework.validation.BindingResult.user'].getFieldError('emailId').defaultMessage : ''}
Did you try <spring:hasBindErrors> tag (I don't understand what you mean writing "without using form taglib")?
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<spring:hasBindErrors name="yourCommandName">
<c:if test="${errors.hasFieldErrors('username')}">
<c:set var="errorClass" value="error" />
</c:if>
</spring:hasBindErrors>
<div class="control-group <c:out value='${errorClass}' />">
Edit after comments:
Inside <spring:hasBindErrors>
tag there is errors
variable (see Errors interface) bound to actual binding errors. You can check if field has errors via errors.hasFieldErrors(fieldName)
.
And really obscure way to get field errors without any tag is requestScope['org.springframework.validation.BindingResult.yourCommandName'].hasFieldErrors('username')
...