Thursday, May 23, 2013

How to write Custom JSR 303 Validation using ConstraintValidator

What is JSR 303?
JSR 303 is Java Bean Validation framework which comes as part of J2EE 6. So in order to use classes specified by them, for Validation you need to include javaee-api jar Ex. javaee-api-7.0.jar

Requirement :
Consider that I want to write my own custom validation to validate email. Ya, there is already email validator provided by Hibernate as part of Hibernate 4.2 but this is just for eample. and you can create own validation to validate FileName or any other validation you like.

Steps to create Custom Validation to validate Email :
1. Create Interface - @interface
2. Create Custom Validation Implementation class using ConstraintValidator
3. Apply Custom Annotation to Bean(Pojo) but it can be any where on Constructor,Method,parameter,Field etc based on how you have added ElementType in @Target

Java Program to create Custom JSR Validation to validate Email Address:

package com.anuj.core.validations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

 * @author Anuj
public @interface ValidEmail {
 String message();

    Class[] groups() default {};
    Class[] payload() default {};
please refer to how to validate Email Address in Java

package com.anuj.core.validations;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

 * @author Anuj
public class EmailValidator implements ConstraintValidator {

 private static String EMAIL_PATTERN = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
 Pattern pattern;
 Matcher matcher;
 public void initialize(ValidEmail email) {
  pattern = Pattern.compile(EMAIL_PATTERN,Pattern.CASE_INSENSITIVE);  

 public boolean isValid(String email, ConstraintValidatorContext context) {
  boolean isValidEmail = false;
  CharSequence emailstr = email; 
  matcher = pattern.matcher(emailstr);
   isValidEmail = true;
  return isValidEmail;

package com.anuj.core.entity;
import com.anuj.core.validations.ValidEmail;

 * @author Anuj
public class Customer {

 String customerId;
 String customerName;
 @ValidEmail(message="Email must be Valid")
 String email;
 public String getCustomerId() {
  return customerId;
 public void setCustomerId(String customerId) {
  this.customerId = customerId;
 public String getCustomerName() {
  return customerName;
 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 public String getEmail() {
  return email;
 public void setEmail(String email) { = email;

Sample JUnit
package com.anuj.core.test;

import static org.junit.Assert.*;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import com.anuj.core.entity.Customer;

public class ValidEmailTest {

 private static Validator validator;
 public static void setUp() throws Exception {
   ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
   validator = validatorFactory.getValidator();

 public void ValidEmailTest() {
  Customer customer = new Customer();
  Set> constraintViolations = validator.validate(customer);
  for(ConstraintViolation constraintViolation : constraintViolations){
   String message = constraintViolation.getMessage();


Author : Anuj Patel
LinkedIn :
Blog :

No comments:

Post a Comment