Thursday 8 April 2021

Bean Validation: Create Custom Composite Constraint

@NotNull

@Size(min = 2, max = 30)

@Pattern(regexp = "[a-zA-Z ] *")

private String name;

 

As you see above definition, name is constrained with annotations like @NotNull, @Size and @Pattern. Instead of adding all these 3 constrains on the property 'name', we can create new constraint 'EmployeeNameConstraint' with all the required constraints and use it.

 

For example, I created 'EmployeeNameConstraint' like below.

 

EmployeeNameConstraint.java

@NotNull
@Size(min = 2, max = 30)
@Pattern(regexp = "[a-zA-Z ] *")
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {})
public @interface EmployeeNameConstraint {
	String message() default "Employee name must be minimum 2 characters, maximum 30 characterrs and must not be null, contain spaces, a-z, A-Z only chars";

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

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

Employee.java

package com.sample.app.model;

import com.sample.app.constraints.EmployeeNameConstraint;

public class Employee {

	private int id;

	@EmployeeNameConstraint
	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, "Rama Krishna");
		System.out.println("Validation Errors for emp2");
		validateBean(emp2);
		
		Employee emp3 = new Employee(3, "");
		System.out.println("Validation Errors for emp3");
		validateBean(emp3);
	}
}


Run App.java, you will see below messages in console.

Validation Errors for emp1
************************************
name,must match "[a-zA-Z ] *"

Validation Errors for emp2
************************************
name,must match "[a-zA-Z ] *"

Validation Errors for emp3
************************************
name,size must be between 2 and 30
name,must match "[a-zA-Z ] *"






 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment