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:

ValidEmail.Java
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
 *
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.CONSTRUCTOR,ElementType.PARAMETER,ElementType.ANNOTATION_TYPE})
@Constraint(validatedBy=EmailValidator.class)
public @interface ValidEmail {
 
 String message();

    Class[] groups() default {};
    
    Class[] payload() default {};
}

EmailValidator.java
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;
 
 @Override
 public void initialize(ValidEmail email) {
  pattern = Pattern.compile(EMAIL_PATTERN,Pattern.CASE_INSENSITIVE);  
 }

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

}

Customer.java
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) {
  this.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;
 
 @BeforeClass
 public static void setUp() throws Exception {
   ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
   validator = validatorFactory.getValidator();
 }

 @Test
 public void ValidEmailTest() {
  Customer customer = new Customer();
  customer.setCustomerId("1");
  customer.setCustomerName("anuj");
  customer.setEmail("anuj@gmail.com");
  //customer.setEmail("anuj@gmail");
  
  Set> constraintViolations = validator.validate(customer);
  for(ConstraintViolation constraintViolation : constraintViolations){
   String message = constraintViolation.getMessage();
   System.out.println(message);
  }
  
  assertEquals(0,constraintViolations.size());
  
 }

}


Author : Anuj Patel
LinkedIn : http://www.linkedin.com/in/anujjpatel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment