In this article we will explain the Spring MVC error tag and its usage. A Spring MVC error tag is normally used for showing any validation error during validating/submitting the data on the forms.
Spring MVC Error Tag
A error tag in spring is defined as follows
1 2 3 4 5 |
<tr> <td>First Name:</td> <td><form:input path="firstName" /></td> <td><form:errors path="firstName" /></td> </tr> |
This tag is rendered as a SPAN html tag
1 2 3 4 5 |
<tr> <td>First Name:</td> <td><input name="firstName" type="text" value=""/></td> <td><span name="firstName.errors">Error message to be displayed</span></td> </tr> |
The Error message that needs to be displayed in the Error Tag is set in the Controller or Validator class as shown below
1 2 3 4 5 6 |
public class FirstNameValidator implements Validator { public void validate(Object obj, Errors errors) { <strong>ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required", "Field is required."); </strong> } } |
If we want to display all the errors that are set in the validators then we can use the following path=”*” attribute
If we do not want to display the error message in the SPAN, then we can define the html tag in which we want the error to be displayed
1 |
<form:errors path="firstName" <strong>element="div"</strong> /> |
This will show the error message in a DIV tag as follows
1 |
<div id="firstName.errors">Field is required</div> |
Also we can add external css classes to the error message as shown below
1 |
<form:errors path="firstName" <strong>cssErrorClass="nameErrorClass"</strong>/> |
cssErrorClass would be translated in class attribute as shown below
1 |
<span id="firstName.errors" class="nameErrorClass">Field is required</span> |
Please do let see the other form tags that are used.