使用Integer字段进行Hibernate验证

时间:2016-07-28 15:09:25

标签: java hibernate spring-mvc

我正在研究hibernate-validator和validation-api库,我想验证类型为Integer的字段名称,当用户输入String类型时,我的问题就出现了。它适用于null和空。如果你曾经有这个问题,你能告诉我解决它的方法吗?

@Entity
@Table(name = "shops")
public class Shop {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    @Column(name = "employees_number")
    private Integer emplNumber;

    // getter and setter

}

@Component
public class ShopValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return Shop.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Shop shop = (Shop) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "shop.name.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emplNumber", "shop.emplNumber.empty");
        if (!NumberUtils.isNumeric(shop.getEmplNumber().toString())) {
            errors.rejectValue("emplNumber", "shop.emplNumber.invalid");
        }
    }

}

public class NumberUtils {

    public static boolean isNumeric(String isNum) {
        try {
            return isNum.matches("[1-9]+");
        } catch (NullPointerException e) {
            return false;
        }
    }
}

Here is picture I need to validate

1 个答案:

答案 0 :(得分:1)

尝试@Digits@NotBlank注释

@Entity
@Table(name = "shops")
public class Shop {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    @Column(name = "employees_number")
    @NotBlank(message = "{shop.name.empty}")
    @Digits(integer=10, fraction=0, message = "{shop.emplNumber.invalid}")
    private String emplNumber;

    // getter and setter
}

http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-defineconstraints-spec