Bean Validation : Hibernate Validator framework

Bean Validation with Hibernate Validator framework

JSR 303

This JSR will define a meta-data model and API for JavaBeanTM validation based on annotations, with overrides and extended meta-data through the use of XML validation descriptors. http://jcp.org/en/jsr/detail?id=309

JSR 349

Bean Validation standardizes constraint definition, declaration and validation for the Java platform. For more information on Bean Validation and how to participate, check out http://beanvalidation.org. http://jcp.org/en/jsr/detail?id=349 

Hibernate Validator

Hibernate Validator 5.x is the reference implementation for JSR 349 - Bean Validation 1.1 of which Red Hat is the specification lead.http://www.hibernate.org/subprojects/validator.html

Sample Implementation.

In the sample implementation, we have a class User.java with validation annotations. A test class to validate the object and to print the error messages at the console. The code is completely self explanatory.

User.java


package com;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.Email;

public class User {

	private String firstName;
	private String lastName;
	
	@Max(message="Age should be max 2 digits", value = 2)
	private short age;
	private String email;
	private Date dob;
		
	
	@Pattern(regexp = "\\d{2}\\\\\\d{2}\\\\\\d{4}", message="Invalid date")
	public String getDateString(){
		String dateString = new SimpleDateFormat("dd\\mm\\yyyy").format(dob);
		System.out.println("DateString :: "+dateString);
		return dateString;
	}
	
	@NotNull(message="First name is mandatory.")
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	@Pattern(regexp="[a-zA-Z]{1,5}$",message="Last name should not contain special characters")
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public short getAge() {
		return age;
	}
	public void setAge(short age) {
		this.age = age;
	}
	@Email(message="Not a valid email address")
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	public Date getDob() {
		return dob;
	}
	public void setDob(Date dob) {
		this.dob = dob;
	}
	
	
}

ValidatorTest.java

package com;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class ValidatorTest {
	
	
	public static void main(String[] args) {
		validate();
	}

	public static void validate(){
		User user = new User();
		user.setEmail("abcd");
		user.setLastName("horos");
		user.setAge((short)123);
		user.setDob(new java.util.Date());
		
		ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
		Validator validator = vf.getValidator();
		
		Set<ConstraintViolation<User>> violations = validator.validate(user);
		
		for(ConstraintViolation<User> c: violations){
			System.out.println(c.getPropertyPath() +" - "+  c.getMessage());
		}
	}
}

Output

INFO Version:27 - HV000001: Hibernate Validator 5.0.1.Final                                                          
DateString :: 03\21\2013
age - Age should be max 2 digits
email - Not a valid email address
firstName - First name is mandatory.

Comments

Post a Comment

Popular posts from this blog

SVN File Creation Date

Java NIO2 - Watching a directory for changes. FileWatcherService.

Log4j multiple WAR files in single EAR configuration