How to check if an error has occurred in a specific property using spring mvc
I am using a form tag.
<form:form commandName="foo"> <div class="myclass "> <label>Foo</label> <form:input path="fooName"/> </div> <div class="controls"> <input type="submit" class="btn" value="Submit"/> </div> </form:form> Question
Is there a way to find out if an error has occurred in a specific field?
I am aware of <form:erros path="fooName"/> , but this will display an error message. I'm for something that just returns true or false based on whether an error occurred in the fooName property. I need this because if an error occurs, I can insert the css error class next to my class
Yes, it is possible:
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <form:form commandName="foo"> <spring:bind path="fooName"> <div class="myclass ${status.error ? 'error' : ''}"> <label>Foo</label> <form:input path="fooName"/> </div> </spring:bind> <div class="controls"> <input type="submit" class="btn" value="Submit"/> </div> </form:form> When you enclose the field inside <spring:bind> , you have access to the implicit status variable of type BindStatus . You can use it to verify that the field has an error or not.
You can also find useful links:
Here is another way with <spring:hasBindErrors> (inside it you have access to the errors variable of type errors ), which will only work in a JSP 2.2 environment:
<spring:hasBindErrors name="foo"> <div class="myclass ${errors.hasFieldErrors('fooName') ? 'error' : ''}"> <label>Foo</label> <form:input path="fooName"/> </div> </spring:hasBindErrors>