我正在研究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;
}
}
}
答案 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
}