Spring MVC Form Check if a field has an error
In this article, we will show you few Spring form tag examples to check if a field has an error message. Review the following Spring MVC bean validation example :
Technologies used :
- Spring 4
- JSTL 1.2
//Bean validation import org.hibernate.validator.constraints.NotEmpty; public class User { @NotEmpty String name; //... //Controller class @RequestMapping(value = "/users", method = RequestMethod.POST) public String saveOrUpdateUser( @ModelAttribute("userForm") @Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { //... } else { //...
1. form:errors
If ‘name’ field has an error message, you can display it via form:errors
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:form method="post" modelAttribute="userForm" action="${userActionUrl}"> <label>Name</label> <form:input path="name" type="text" id="name" /> <form:errors path="name" /> </form:form>
2. spring:bind and form:errors
With spring:bind, you can use ${status.error} to check if the ‘name’ field has an error, and display different CSS class conditionally.
<form:form method="post" modelAttribute="userForm" action="${userActionUrl}"> <spring:bind path="name"> <div class="form-group ${status.error ? 'has-error' : ''}"> <label>Name</label> <form:input path="name" type="text" id="name" /> <form:errors path="name" /> </div> </spring:bind> </form:form>
The error message is still displayed via form:errors, but this way you get more controls.
3. c:set and form:errors
Same like example 2, instead, you use c:set to check if the ‘name’ field has an error message.
<form:form method="post" modelAttribute="userForm" action="${userActionUrl}"> <c:set var="nameHasBindError"> <form:errors path="name"/> </c:set> <div class="form-group ${not empty nameHasBindError?"has-error":""}"> <label>Name</label> <form:input path="name" type="text" id="name" /> ${nameHasBindError} </div> </form:form>
This example is a bit weird, but it works.
4. Display all errors
To display all the error messages in the submitted form, use spring:hasBindErrors and loop the ${errors.allErrors}
<spring:hasBindErrors name="userForm"> <c:forEach var="error" items="${errors.allErrors}"> <b><spring:message message="${error}" /></b> <br /> </c:forEach> </spring:hasBindErrors>
Alternatively, use path="*"
<form:form method="post" modelAttribute="userForm" action="${userActionUrl}"> <form:errors path="*" class="has-error" /> </form:form>
References
- Spring Tags – bind tag and hasBindErrors tag
- Spring MVC form handling example
- Spring MVC and JSR 303 @Valid bean validation example
From:一号门
COMMENTS