Saturday 10 April 2021

Bean Validation: Create custom validation constraint

Step 1: Create an annotation and specify the class that validates the information.

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { EmployeeNameChecker.class })
public @interface EmployeeNameConstraint {
	.....
	.....
}

'EmployeeNameChecker' class is used to validate the annotation.

 

Step 2: Define EmployeeChecker class by implementing ConstraintValidator interface.

public class EmployeeNameChecker implements ConstraintValidator<EmployeeNameConstraint, String> {

	@Override
	public void initialize(EmployeeNameConstraint empNameConstraint) {
		......
		......
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		......
		......
		......
	}

}

 

Find the below working application.

 

EmployeeConstraint.java

 

package com.sample.app.constraints;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { EmployeeNameChecker.class })
public @interface EmployeeNameConstraint {
	String message() default "Employee name is not matched";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};

	int minSize() default 10;

	String regex();
}


EmployeeNameChecker.java

package com.sample.app.constraints;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EmployeeNameChecker implements ConstraintValidator<EmployeeNameConstraint, String> {
	EmployeeNameConstraint empNameConstraint;

	@Override
	public void initialize(EmployeeNameConstraint empNameConstraint) {
		this.empNameConstraint = empNameConstraint;
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if (value == null) {
			return false;
		}

		int minimumSize = empNameConstraint.minSize();
		if (value.length() < minimumSize) {
			return false;
		}

		String regex = empNameConstraint.regex();

		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(value);

		return matcher.matches();

	}

}


Employee.java

package com.sample.app.model;

import com.sample.app.constraints.EmployeeNameConstraint;

public class Employee {

	private int id;

	@EmployeeNameConstraint(minSize = 2, regex = "[a-zA-Z ]*", message = "Employee name must be >= 2 characters and contain only a-z, A-Z characters")
	private String name;

	public Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

}


App.java

package com.sample.app;

import java.util.Set;

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

import com.sample.app.model.Employee;

public class App {
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	private static Validator validator = validatorFactory.getValidator();

	private static void validateBean(Employee emp) {
		System.out.println("************************************");
		Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

		if (validationErrors.size() == 0) {
			System.out.println("No validation errors....");
		}

		for (ConstraintViolation<Employee> violation : validationErrors) {
			System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
		}
		System.out.println("");
	}

	public static void main(String args[]) {
		Employee emp1 = new Employee(1, "Ram");
		System.out.println("Validation Errors for emp1");
		validateBean(emp1);
		
		Employee emp2 = new Employee(2, "RamaKrishna1");
		System.out.println("Validation Errors for emp2");
		validateBean(emp2);
		
		Employee emp3 = new Employee(3, "");
		System.out.println("Validation Errors for emp3");
		validateBean(emp3);
	}
}


Output

Validation Errors for emp1
************************************
No validation errors....

Validation Errors for emp2
************************************
name,Employee name must be >= 2 characters and contain only a-z, A-Z characters

Validation Errors for emp3
************************************
name,Employee name must be >= 2 characters and contain only a-z, A-Z characters








  

Previous                                                    Next                                                    Home

No comments:

Post a Comment