gpt4 book ai didi

java - 如何在 hibernate validator 引擎中指定时间范围?

转载 作者:行者123 更新时间:2023-11-30 05:33:30 24 4
gpt4 key购买 nike

我有一个 java.time.LocalDate 类型的字段。它存储我的用户的出生日期...

@Past
@Column(nullable=false)
private LocalDate dateOfBirth;

我最近在我的 Maven 项目中包含了 hibernate validator。我知道有一个名为 @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");

我正在我的 Controller 类中使用 @ExceptionHandler spring 注释捕获异常。但是我的帐户验证服务中有很多代码,所以我想使用这些标签。

是否可以使用 hibernate validator 引擎来做到这一点?

最佳答案

不,在这种情况下您不能使用@Past

对于涉及自定义逻辑的此类 validator ,您可以构建自己的 validator :这是您可以遵循的示例 https://www.baeldung.com/spring-mvc-custom-validator

您还应该使用 javax.validations 中的 validator ,因为这是标准验证库

关于java - 如何在 hibernate validator 引擎中指定时间范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com