What are we going to build?
User input validation for the new car form.
Validator
This Validator class will validate a Car: 'WEB-INF/src/springmvc/validator/CarValidator.java'
package springmvc.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import springmvc.model.Car;
public class CarValidator implements Validator {
public boolean supports(Class aClass) {
return Car.class.equals(aClass);
}
public void validate(Object obj, Errors errors) {
Car car = (Car) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "model", "field.required", "Required field");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "field.required", "Required field");
if ( ! errors.hasFieldErrors("price")) {
if (car.getPrice().intValue() == 0)
errors.rejectValue("price", "not_zero", "Can't be free!");
}
}
}
-
supports(): declare classes supported by this validator
-
To add an error these parameters are needed:
-
Car field name
-
error message key
-
default message if no message is not found for the key
-
View
Let's update the view 'jsp/carNew.jsp':
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <title>New Sponsor</title> <style> .error { color: red; } </style> </head> <body> <h1>New Car</h1> <form:form method="post"> Brand<br /> <form:select path="brand"> <form:options items="${brandList}" itemLabel="name" itemValue="id" /> </form:select> <br /><br /> Model <form:errors path="model" cssClass="error"/><br /> <form:input path="model"/><br /><br /> Price <form:errors path="price" cssClass="error"/><br /> <form:input path="price"/><br /><br /> <input type="submit" value="Submit"> </form:form> </body> </html>
Configuration
We now declare the validator for the URL addCar.html in 'WEB-INF/springmvc-servlet.xml'
<bean name="/new_car.html" class="springmvc.web.CarNewController"> <property name="commandClass" value="springmvc.model.Car"/> <property name="formView" value="carNew"/> <property name="successView" value="list_cars.html"/> <property name="validator"> <bean class="springmvc.validator.CarValidator"/> </property> </bean>
Result
Build (ant) and relaunch Tomcat:http://localhost:8180/springmvc/new_car.html
We can check it's working by entering empty values:
from: http://jeromejaglale.com/doc/java/spring/form_validation