value - spring mvc validation example without annotation




How to access Spring 3 MVC validator results in JSP without using form taglib (3)

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')...

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 of my HTML:

<div class="control-group error"> <!-- HERE: binding.hasErrors() ? "error" : "" -->
    <form:label path="username" cssClass="control-label">User Name</form:label>
    <div class="controls">
        <form:input path="username" cssClass="span3"/>
        <form:errors path="username" cssClass="help-inline" />
    </div>
</div>

So on the first line the class attribute has two classes "control-group" and "error". I need to add error class only if that field has an error associated with it. I know the WebDataBinder is included in the page somehow, but I don't know how to access it. Essentially I just want to execute some good old fashion <%= binding.hasError() ? "error" : "" %>, but how do I get access to the binder in the page?


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 : ''}

Need to Combine Spring Binding Errors and Custom Exceptions into Same DIV

I got some clues from this thread: How to access Spring 3 MVC validator results in JSP without using form taglib , and here's the working result:

    <c:if test="${fn:length(requestScope.exceptions) > 0 || 
requestScope['org.springframework.validation.BindingResult.model'].hasFieldErrors()}">

The 2nd part of this condition checks for Binding Errors even prior to the tag Spring:hasBindErrors.