Javax Bean 验证:@Max 和@Min 不工作

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

我有以下型号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;
    }

以下是测试 class,我在其中验证 Person 模型 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());

            }
        }
    }}

尽管 fname 字段的值只有 7 个字符长,但它显示以下验证消息。

姓氏应至少包含 5 个字符。::lname::姓氏应至少包含 5 个字符。 名字应小于 10 个字符。::fname::名字应小于 10 个字符。

这不是正确的注释。 @Min@Max 用于 BigDecimalBigIntegerbyteshortintlong 及其各自的包装。

请改用@Sizejavadoc 的摘录:

Supported types are:

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