Home > Net >  One field depends on another in thymeleaf with spring boot
One field depends on another in thymeleaf with spring boot

Time:01-19

I have a spring boot application using thymeleaf. On the front end page I have an input field named calulatedValue and followed by another field name OverridingValue. The validation should be that the OverridingValue is always less than the calculatedValue. For example the calculatedValue is 2 the OverridingValue should be less than 2. In case the user enters an value >=2, there should be one error message for him on the form. How can I achieve this validation using thymeleaf and spring boot.

CodePudding user response:

In your template.html:

        <div th:if="${error}">
            <div>
                <span th:utext="${error}"></span>
            </div>
        </div>

In your Controller.java:

@GetMapping("/{calculatedValue}/{overridingValue}")
public String checkValues(final RedirectAttributes redirectAttributes, @RequestParam("calculatedValue") Integer calculatedValue, @RequestParam("overridingValue") Integer overridingValue) {
    if (calculatedValue >= overridingValue) {
        redirectAttributes.addFlashAttribute("error", "Invalid number!");
        return "redirect:/";
    }
    return "template";
}
  • Related