我有一个java.time.LocalDate类型的字段。它为我的用户存储出生日期...
@Past
@Column(nullable=false)
private LocalDate dateOfBirth;
我最近在我的 maven 项目中包含了休眠验证器。我知道有一个注释叫做@Past,但我看到它不能接受任何参数。我希望我的用户的出生日期在过去 100 年到 3 年之间。
我目前正在我的服务类中检查这一点,如下所示:
LocalDate dateOfBirth = account.getDateOfBirth();
if(dateOfBirth == null) throw new SignupFormException("Date of Birth is required!", "dateOfBirth");
LocalDate now = LocalDate.now();
Period age = Period.between(dateOfBirth, now);
if(age.getYears() > 100) throw new SignupFormException("Invalid date of birth!", "dateOfBirth");
if(age.getYears() < 3 && !age.isNegative()) throw new SignupFormException("Age too low!", "dateOfBirth");
if(age.isNegative()) throw new SignupFormException("Invalid date of birth!", "dateOfBirth");
我在我的控制器类中使用@ExceptionHandler弹簧注释捕获异常。但是我的帐户验证服务中有很多代码,所以我想使用这些标签。
是否可以使用休眠验证器引擎执行此操作?
不,在这种情况下不能使用 @Past
对于涉及自定义逻辑的此类验证器,您可以构建自己的验证器:这里有一个你可以遵循的示例 https://www.baeldung.com/spring-mvc-custom-validator
您还应该使用javax.validations
验证器,因为这是标准的验证库