两个日期字段之间的Spring验证?

scyqe7ek  于 2024-01-05  发布在  Spring
关注(0)|答案(4)|浏览(131)

在我的Spring应用程序中,我使用Hibernate Validator进行验证。
当我做简单的验证,如@NotEmpty@Email ..我很容易工作
但是当进入日期字段时,给出问题.
问题是,在我的JSP页面,我得到的值类型为字符串,然后我将字符串转换为日期。
听是我的榜样……

  1. @NotEmpty(message = "Write Some Description")
  2. private String description;
  3. private String fromDateMonth;
  4. private String fromDateYear;
  5. private String toDateMonth;
  6. private String toDateYear;

字符串
我在我的Controller类中将fromDateMonthfromDateYear转换为Date。
那么他们是否有可能在Controller类中添加Validator Annotation呢?
其他明智的我应该做什么听到?给予我的建议.

gcmastyq

gcmastyq1#

如果你想验证fromDate在toDate之前,你可以写一个自定义的验证器来执行这个多字段验证。你写一个自定义的验证器,你还定义了一个自定义的annotation,它被放置在被验证的bean上。
有关详细信息,请参阅以下答案。

mtb9vblg

mtb9vblg2#

根据问题显示的次数,我得出结论,很多人仍然在这里寻找一个日期范围的验证器。
假设我们有一个DTO包含另一个DTO(或带有@Embeddable注解的类),其中两个字段带有LocalDate(或其他日期表示,这只是示例)。

  1. class MyDto {
  2. @ValidDateRange // <-- target annotation
  3. private DateRange dateRange;
  4. // getters, setters, etc.
  5. }

个字符
现在,我们可以声明自己的@ValidDateRange注解:

  1. @Documented
  2. @Constraint(validatedBy = DateRangeValidator.class)
  3. @Target({ElementType.FIELD})
  4. @Retention(RetentionPolicy.RUNTIME)
  5. @interface ValidDateRange {
  6. String message() default "Start date must be before end date";
  7. Class<?>[] groups() default { };
  8. Class<? extends Payload>[] payload() default { };
  9. }


编写验证器本身也可以归结为几行代码:

  1. class DateRangeValidator implements ConstraintValidator<ValidDateRange, DateRange> {
  2. @Override
  3. public boolean isValid(DateRange value, ConstraintValidatorContext context) {
  4. return value.getStartOfRange().isBefore(value.getEndOfRange());
  5. }
  6. }

展开查看全部
2guxujil

2guxujil3#

为了确保您可以在控制器中使用Bean验证,只需像在模型中那样在属性上添加一个注解。但最好的方法是在模型中使用Date类型而不是string。

3qpi33ja

3qpi33ja4#

参考:https://blog.tericcabrel.com/write-custom-validator-for-body-request-in-spring-boot/
创建DateRange标注

  1. @Constraint(validatedBy = DateRangeValidator.class)
  2. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Documented
  5. public @interface DateRange {
  6. String message() default "{mob.concept.admin.models.constraint.DateRange.message}";
  7. Class<?>[] groups() default {};
  8. Class<? extends Payload>[] payload() default {};
  9. String before();
  10. String after();
  11. }

字符串

创建验证器约束

  1. public class DateRangeValidator implements ConstraintValidator<DateRange, Object> {
  2. private String beforeFieldName;
  3. private String afterFieldName;
  4. @Override
  5. public void initialize(DateRange constraintAnnotation) {
  6. beforeFieldName = constraintAnnotation.before();
  7. afterFieldName = constraintAnnotation.after();
  8. }
  9. @Override
  10. public boolean isValid(final Object value, ConstraintValidatorContext context) {
  11. try {
  12. final Field beforeDateField = value.getClass().getDeclaredField(beforeFieldName);
  13. beforeDateField.setAccessible(true);
  14. final Field afterDateField = value.getClass().getDeclaredField(afterFieldName);
  15. afterDateField.setAccessible(true);
  16. final LocalDate beforeDate = (LocalDate) beforeDateField.get(value);
  17. final LocalDate afterDate = (LocalDate) afterDateField.get(value);
  18. return beforeDate.isEqual(afterDate) || beforeDate.isBefore(afterDate);
  19. } catch (NoSuchFieldException | IllegalAccessException ignored) {
  20. return false;
  21. }
  22. }
  23. }

示例

  1. @DateRange(before = "startDate", after = "endDate", message = "Start date should be less than end date")
  2. public class OfferDto {
  3. @NotNull(message = "offer title required")
  4. @Size(max = 20, min = 8, message = "Offer title must be between 8 and 20 characters")
  5. private String offerTitle;
  6. @Size(max = 100, min = 8, message = "Offer title must be between 8 and 100 characters")
  7. @NotNull(message = "offer description required")
  8. private String description;
  9. @NotNull(message = "start date is required")
  10. private LocalDate startDate;
  11. @NotNull(message = "end date is required")
  12. private LocalDate endDate;
  13. @NotNull(message = "discount is required")
  14. private Float discount;
  15. @NotNull(message = "offer type is required")
  16. @EnumValidation(enumsClass = OfferType.class)
  17. private String offerType;
  18. }

展开查看全部

相关问题