简体   繁体   English

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

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

I have a class with this field in: 我在这个领域有一个班级:

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

I created two LocalDate variables which I want to check between (for example) 我创建了两个我想检查的LocalDate变量(例如)

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

I was using @PastOrPresent but that does not stop users from entering a date like year 3050. 我使用的是@PastOrPresent,但这不会阻止用户输入3050年这样的日期。

I started making a method in the domain class, where the passDate field resides, however I really do not know where the validation goes and how to call this validation method. 我开始在passDate字段所在的域类中创建一个方法,但是我真的不知道验证在哪里以及如何调用此验证方法。 (Here is a snippet of what I was trying to do but unsure where to put it? (maybe its wrong too!)) (以下是我正在尝试做的一小段,但不确定放在哪里?(也许也是错误的!)

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

Wasn't sure where this goes? 不确定会去哪里? What method? 什么方法 How do I call this validation? 我如何称呼此验证? or is there another way. 还是有另一种方式。 I have looked online for so long and can't figure out what to do. 我已经在网上寻找了很长时间,不知道该怎么办。 I have a thymeleaf form with this field (which was using the PastOrPresent validation to return an error message on submit) 我有一个带有此字段的百里香表单(正在使用PastOrPresent验证在提交时返回错误消息)

            <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>

Here is the post controller 这是职位控制器

@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";
    }

}

Where examformservice is a class variable of my service which links to my repository which is 其中exformformservice是我的服务的类变量,它链接到我的存储库,即

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

}

Where would I put the validation? 我将验证放在哪里? and what would the input be? 输入的是什么?

You need to check this before you assign it to the field. 您需要先进行检查,然后再将其分配给该字段。 So in your form submit you do something like that: 因此,在您的表单提交中,您需要执行以下操作:

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

If you want a JSR annotation you can work your way from this one: 如果您想要一个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();
}

And its validator: 及其验证器:

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;
    }
}

The above is exclusive (the exact date will be invalid), you may want to tweak it. 以上是排他性的(确切日期将无效),您可能需要对其进行调整。

To use it is only to add annotation in model bean: 要使用它,只需在模型bean中添加注释:

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

The inverse ( @Before ) I leave you as an exercise :) 相反( @Before )我让您练习:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM