Sunday 28 March 2021

Bean Validation: DecimalMin: Value must be >= this value

 

If you annotate any number with @DecimalMin annotation, then the number must be higher or equal to the specified minimum.

 

Example

@DecimalMin(value = "500")

private int id;

 

What are the supported types?

a.   byte,

b.   short,

c.    int,

d.   long,

e.   Byte,

f.     Short,

g.   Integer,

h.   Long,

i.     BigDecimal,

j.     BigInteger,

k.    CharSequence

 

Note: As per specification double, float is not supported due to rounding errors. Some providers may provide some approximative support

 

Where can I apply this annotation?

a.   METHOD,

b.   FIELD,

c.    ANNOTATION_TYPE,

d.   CONSTRUCTOR,

e.   PARAMETER,

f.     TYPE_USE

 

Find the below working application.

 

Employee.java 

package com.sample.model;

import javax.validation.constraints.DecimalMin;

public class Employee {

	@DecimalMin(value = "500")
	private int id;

	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;
	}

	public String getName() {
		return name;
	}

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

}

 

Test.java

package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.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(123, "Krishna");
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(23456789, "Siva");
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);
	}
}

 

Output

Validation errors on bean emp1
************************************
id,must be greater than or equal to 500

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

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment