2

我有以下模型类

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

以下是我正在验证 Person 模型类的测试类。

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 个字符。

4

1 回答 1

11

这不是正确的注释。@Min并且@MaxBigDecimal, BigInteger, byte, short, int,long和它们各自的包装器。

@Size改用。javadoc的摘录:

支持的类型有:

  • 字符串(评估字符串长度)
  • 集合(评估集合大小)
  • 地图(评估地图大小)
  • 数组(评估数组长度)
于 2017-10-16T08:44:13.443 回答