如何使用 Springboot 和 Thymeleaf 使用 LocalTime 在两个日期之间进行验证

How do I validate between two dates using LocalTime using Springboot and Thymeleaf

我有一个 class 这个字段在:

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate passDate;

我创建了两个 LocalDate 变量,我想在它们之间进行检查(例如)

LocalDate a = LocalDate.of(1995, 1, 01); LocalDate b = LocalDate.of(2140, 12, 31);

我使用的是@PastOrPresent,但这并不能阻止用户输入 3050 年这样的日期。

我开始在 passDate 字段所在的域 class 中创建一个方法,但是我真的不知道验证去哪里以及如何调用此验证方法。 (这是我正在尝试做但不确定放在哪里的片段?(也许它也错了!))

if (!(passDate.isBefore(a) && passDate.isAfter(b))) {
return passDate; }

不确定这是怎么回事?什么方法?我该如何称呼此验证?或者还有其他方法。我在网上看了很长时间,不知道该怎么办。 我有一个带有此字段的 thymeleaf 表单(使用 PastOrPresent 验证 return 提交时出现错误消息)

            <div class="form-group">
                <label for="pass_date">Enter the pass date</label>
                <input type="date" th:field="*{passDate}" name="pass_date" id="pass_date"
                       class="form-control"/>
                <p class="text-danger" th:if="${#fields.hasErrors('passDate')}" th:errors="*{passDate}"></p>
            </div>

这里是 post 控制器

@PostMapping("/admin/examform")
public String createExamForm(@ModelAttribute("examform") @Valid Examform examform,
                                    BindingResult bindingResult,
                                    @AuthenticationPrincipal final User user, Model model){
    if (bindingResult.hasErrors()) {
        System.out.println(bindingResult.getAllErrors());
        model.addAttribute("examform", examform);
        return "examformhtml";
    }else{
        examformservice.createExamForm(examform);
        model.addAttribute("loggedInUsername", user.getUsername());
        return "examformsuccess";
    }

}

其中 examformservice 是我服务的一个 class 变量,它链接到我的存储库

@Override
public void createExamForm(Examform examform) {
    String sql = "UPDATE examform SET passDate=? WHERE studentId=?";
    jdbcTemplate.update(sql, examform.getPassDate(), examform.getStudentId());

}

我应该把验证放在哪里?输入是什么?

您需要在将其分配给该字段之前进行检查。所以在你的表单中提交你做这样的事情:

LocalDate input = ...;
if (!(input.isBefore(a) && input.isAfter(b))) {
    // set the field
} else {
    // handle error here
    // throw exception or just print something
}

如果你想要一个 JSR 注释,你可以从这个开始:

@Constraint(validatedBy=AfterValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface After {
    String message() default "must be after {value}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    String value();
}

及其验证器:

public class AfterValidator implements ConstraintValidator<After, LocalDate> {

    private LocalDate date;

    public void initialize(After annotation) {
        date = LocalDate.parse(annotation.value());
    }

    public boolean isValid(LocalDate value, ConstraintValidatorContext context) {
        boolean valid = true;
        if (value != null) {
            if (!value.isAfter(date)) {
                valid = false;
            }
        }
        return valid;
    }
}

以上为独家(具体日期无效),您可自行调整。

使用它只需要在模型bean中添加注解即可:

@After("1995-01-01")
private LocalDate passDate;

逆(@Before)留给你做练习:)