Thursday 8 April 2021

Bean Validation: Size: size must be between the specified boundaries

@Size annotation makes sure that the size of the element is within given boundaries.

 

Example

@Size(min = 1, max = 3)

private List<String> hobbies;

 

Supported Types

a.   CharSequence

b.   Collection

c.    Map

d.   Array

 

Where can I apply this annotation?

a.   METHOD

b.   FIELD

c.    ANNOTATION_TYPE

d.   CONSTRUCTOR

e.   PARAMETER

f.     TYPE_USE

 

Employee.java

package com.sample.app.model;

import java.util.List;

import javax.validation.constraints.Size;

public class Employee {

	private int id;

	private String name;

	@Size(min = 1, max = 3)
	private List<String> hobbies;

	public Employee(int id, String name, List<String> hobbies) {
		this.id = id;
		this.name = name;
		this.hobbies = hobbies;

	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<String> getHobbies() {
		return hobbies;
	}

	public void setHobbies(List<String> hobbies) {
		this.hobbies = hobbies;
	}

}

 

Test.java

package com.sample.app;

import java.util.Arrays;
import java.util.Collections;
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 Test {
	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, "Rama Krishna", Arrays.asList("Cricket", "Trekking"));
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(2, "Siva", Collections.EMPTY_LIST);
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);

	}
}

 

Output

Validation errors on bean emp1
************************************
No validation errors....

Validation errors on bean emp2
************************************
hobbies,size must be between 1 and 3

 

 

 

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment