范围时间验证

  1. /**
  2. * 范围时间验证注解
  3. */
  4. @Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE })
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @Constraint(validatedBy = IntervalTimeCheckValidator.class)
  7. @Documented
  8. @Repeatable(IntervalTimeCheck.List.class)
  9. public @interface IntervalTimeCheck {
  10. String[] beginProps() default {"beginTime"};
  11. String[] endProps() default {"endTime"};
  12. String message() default "开始时间不能大于结束时间 ";
  13. Class<?>[] groups() default {};
  14. Class<? extends Payload>[] payload() default {};
  15. @Target({ ElementType.TYPE,ElementType.FIELD,ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
  16. @Retention(RetentionPolicy.RUNTIME)
  17. @Documented
  18. @interface List {
  19. IntervalTimeCheck[] value();
  20. }
  21. }
  1. public class IntervalTimeCheckValidator implements ConstraintValidator<IntervalTimeCheck, Object> {
  2. private String[] beginProps;
  3. private String[] endProps;
  4. @Override
  5. public void initialize(IntervalTimeCheck constraintAnnotation) {
  6. this.beginProps = constraintAnnotation.beginProps();
  7. this.endProps = constraintAnnotation.endProps();
  8. }
  9. @Override
  10. public boolean isValid(Object value, ConstraintValidatorContext context) {
  11. BeanWrapper beanWrapper = new BeanWrapperImpl(value);
  12. boolean valid = true;
  13. for (int i = 0; i < beginProps.length; i++) {
  14. String beginProp = beginProps[i];
  15. String endProp = endProps[i];
  16. Object beginObjVal = beanWrapper.getPropertyValue(beginProp);
  17. Object endObjVal = beanWrapper.getPropertyValue(endProp);
  18. if (ObjectUtils.isNotEmpty(beginObjVal) && ObjectUtils.isNotEmpty(endObjVal)) {
  19. int result = compareDateTime(beginObjVal, endObjVal);
  20. if (result < 0) {
  21. valid = false;
  22. break;
  23. }
  24. }
  25. }
  26. return valid;
  27. }
  28. private int compareDateTime(Object beginObjVal, Object endObjVal) {
  29. int result = 0;
  30. if (beginObjVal instanceof LocalDateTime) {
  31. LocalDateTime beginDateTime = (LocalDateTime) beginObjVal;
  32. LocalDateTime endDateTime = (LocalDateTime) endObjVal;
  33. result = endDateTime.compareTo(beginDateTime);
  34. } else if (beginObjVal instanceof LocalDate) {
  35. LocalDate beginDate = (LocalDate) beginObjVal;
  36. LocalDate endDate = (LocalDate) endObjVal;
  37. result = endDate.compareTo(beginDate);
  38. } else if (beginObjVal instanceof Date) {
  39. Date beginDate = (Date) beginObjVal;
  40. Date endDate = (Date) endObjVal;
  41. result = endDate.compareTo(beginDate);
  42. }
  43. return result;
  44. }
  45. }