【问题标题】:Validation of REST endpoint parameter vs. LocalDate with custom validation使用自定义验证验证 REST 端点参数与 LocalDate
【发布时间】:2017-06-17 11:40:17
【问题描述】:

我已经使用 Spring Boot 构建了一个 REST 服务。在其中一个端点上,我发布了一个请求参数以及其他 2 个参数的日期。发布后,请求参数被绑定到一个对象。日期与LocalDate 字段绑定。在发布之后但在绑定之前,我喜欢使用验证和 Hibernate Validator 来验证请求参数。 LocalDate 没有可用的验证,因此我需要为 LocalDate 编写自定义验证。

这是发布到端点的内容:

/parameter-dates?parameterDateUnadjusted=2017-02-29&limit=5&direction=d

这里是端点的代码:

@GetMapping(value = "/parameter-dates")
public ResponseEntity getParameterDates(@Valid ParameterDateRequest parameterDateRequest, Errors errors) {
// DO SOME STUFF
}

这是用于对象的模型:

@Component
@Data
public class ParameterDateRequest {

    @MyDateFormatCheck(pattern = "yyyy-MM-dd", message = "Date not matching")
    LocalDate parameterDateUnadjusted;
    @NotEmpty(message = "Direction can't be empty")
    String direction;
    @Digits(integer=1, fraction=0, message = "Limit has to be an integer of max 100 000")
    int limit;
}

这是验证注解的代码:

@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = MyDateFormatCheckValidator.class)
@Documented
public @interface MyDateFormatCheck {
    String pattern();
    String message();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

这是它自己的验证代码:

public class MyDateFormatCheckValidator implements ConstraintValidator<MyDateFormatCheck, LocalDate> {

    private MyDateFormatCheck check;

    @Override
    public void initialize(MyDateFormatCheck constraintAnnotation) {
        this.check = constraintAnnotation;
    }

    @Override
    public boolean isValid(LocalDate object, ConstraintValidatorContext constraintContext) {
        if (object == null) {
            return true;
        }

        return isValidDate(object, check.pattern());
    }

    public static boolean isValidDate(LocalDate inDate, String format) {
        // TEST IF inDate IS VALID RETURN TRUE/FALSE
    }
}

这是错误的方法吗?我猜parameterDateUnadjusted 实际上是String 而不是LocalDate 当它被发布到端点然后我的验证器应该使用String 作为inDate 但是我需要更改我的@ 模型987654334@ 到字符串,它对程序不起作用,因为它作为LocalDate 使用它。我不太确定在这里做什么。有什么建议吗?

【问题讨论】:

  • 我在同一条船上。碰巧解决了这个问题?

标签: java validation spring-boot bean-validation hibernate-validator


【解决方案1】:

我认为您正在寻找的是 - DateTimeFormat 注释。当值已经绑定到LocalDate 时,验证日期格式是没有意义的。

【讨论】:

    猜你喜欢
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多