javabean-validationhibernate-validatorserver-side-validation

Javax Bean Validation : @Max and @Min is not working


I have following model class

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
public class Person {

    @Max(value = 10, message = "First name should be smaller than 10 characters.")
    private String fname;
    @Min(value = 5, message = "Last name should have atleast 5 characters.")
    private String lname;
    private String status;

    public Person(String fname, String lname, String status) {
        super();
        this.fname = fname;
        this.lname = lname;
        this.status = status;
    }

Following is Test class where I am validating the Person model class.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Set;

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


import the.bhushan.models.Person;

public class Test {

    public static void main(String[] args) throws FileNotFoundException {
        Test test = new Test();
        //test.byXML();
        test.byAnnotation();
    }

    private void byAnnotation() {
        ValidatorFactory validatorFactory = Validation
                .buildDefaultValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        Person emp1 = new Person("Bhushan", "Patil", "A");
        Set<ConstraintViolation<Person>> validationErrors = validator
                .validate(emp1);

        if (!validationErrors.isEmpty()) {
            for (ConstraintViolation<Person> error : validationErrors) {
                System.out.println(error.getMessageTemplate() + "::"
                        + error.getPropertyPath() + "::" + error.getMessage());

            }
        }
    }}

Even though, fname field have value only 7 character long, it is showing following validation message.

Last name should have atleast 5 characters.::lname::Last name should have atleast 5 characters. First name should be smaller than 10 characters.::fname::First name should be smaller than 10 characters.


Solution

  • This is not the correct annotation. @Min and @Max are for BigDecimal, BigInteger, byte, short, int, long and their respective wrappers.

    Please use @Size instead. Extract of javadoc :

    Supported types are:

    • String (string length is evaludated)
    • Collection(collection size is evaluated)
    • Map(map size is evaluated)
    • Array (array length is evaluated)