spring

Spring MVC Form validation with Hibernate validator sample

Follow the post Spring MVC Form validation using Validator, in this tutorial will show you how to validate data submission using Hibernate Validator framework.

1. Dependencies

To using hibernate validator with Spring MVC we need add follow dependencies to pom.xml file

                <dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.0.1.Final</version>
		</dependency>

2.Validate annotation for form

To validate EmployeeForm we define annotation as below

public class EmployeeForm {
	@NotBlank
	private String firstName;
	@NotBlank
	private String lastName;
	@NotBlank
	@Pattern(regexp="[0-9]{10}")
	private String phone;
	private String dob;
	@NotBlank
        @Email
	private String email;
	private String joinDate;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getDob() {
		return dob;
	}

	public void setDob(String dob) {
		this.dob = dob;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getJoinDate() {
		return joinDate;
	}

	public void setJoinDate(String joinDate) {
		this.joinDate = joinDate;
	}

}

To Spring MVC can realize this annotation we need make sure in spring Dispatch Servlet config has follow line

<annotation-driven />

3. Controller

Cause we using Hibernate Validator so we don’t need a callback to config validator so we will delete below function

	@InitBinder(value = "employee")
	public void initBinder(WebDataBinder binder) {
		binder.addValidators(new EmployeeValidator());
	}

4. Define custom message

Spring MVC lookup message code for Hiberante validator message with this formĀ annotationName.model_name.fieldName. To customize default message we need define follow lines in messages.properties

#hibernate validator custom messages
Pattern.employee.phone=Phone is invalid format.
NotBlank.employee.phone=Phone is required
NotBlank.employee.lastName=Last name is required
NotBlank.employee.firstName=First name is required
NotBlank.employee.email=Email name is required
Email.employee.email=Email is invalid format.

5. Run application

Run application with missing or invalid input we will get follow result

6. Source Code

You can get source code of this tutorial on my github or click on this link

Leave a Reply