Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an error happened on a specific property with spring mvc

I'm using the 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 happened on a specific field?

I am aware of the <form:erros path="fooName"/> but this will print out the error message. I am after something that simply returns true or false based on if the error happened on fooName property. I need this because if the error happened then I can insert the css class error next to my class

like image 620
birdy Avatar asked Dec 05 '22 11:12

birdy


1 Answers

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 field inside <spring:bind> tag you have access to implicit variable status of type BindStatus. You may use it to check that field has error or not.

You also probaly find useful following links:

  • Spring MVC and Twitter Bootstrap – customizing the input fields
  • Spring MVC + Bootstrap Errors (extended)

Here is another way with <spring:hasBindErrors> (inside it you have access to errors variable of type Errors) which will work only in environment with JSP 2.2:

<spring:hasBindErrors name="foo">
    <div class="myclass ${errors.hasFieldErrors('fooName') ? 'error' : ''}">
        <label>Foo</label>
        <form:input path="fooName"/>
    </div>
</spring:hasBindErrors>
like image 56
Slava Semushin Avatar answered Dec 28 '22 08:12

Slava Semushin