Cześć mam taki kalkulator BMR:
Zrobiłem na klasie modelowej walidację jednak problem jest po stronie kontrolera , coś źle piszę , czegoś brakuje... w każdym razie walidacja nie działa
Formularz wygląda tak (plik bmrform)
<form class="list-inline" th:object="${operationModel}" th:action="@{/bmr}" th:method="post" >
<div class="form-group" >
<label class="control-label">Wzrost:</label>
<input type="text" class="form-control" th:field="*{height}" placeholder="Wzrost w centymetrach"/>
<p th:if="${#fields.hasErrors('height')}" th:errors="*{height}"/>
</div>
<div class="form-group" >
<label class="control-label">Masa ciała:</label>
<input type="text" class="form-control" th:field="*{bodyweight}" placeholder="Masa ciała w kg"/>
<p th:if="${#fields.hasErrors('bodyweight')}" th:errors="*{bodyweight}"/>
</div>
<div class="form-group" >
<label class="control-label">Wiek:</label>
<input type="text" class="form-control" th:field="*{age}" placeholder="Wiek"/>
<p th:if="${#fields.hasErrors('age')}" th:errors="*{age}"/>
</div>
Metody w kontrolerze
@RequestMapping("/bmr")
public String createOperationModel(Model model) {
model.addAttribute("operationModel", new CalculatorFromBmr());
return "bmrform";
}
@RequestMapping(path="/bmr", method = RequestMethod.POST)
public String add(@ModelAttribute("operationModel") CalculatorFromBmr calculatorFromBmr, Model model) {
model.addAttribute("result", calculatorBmr.calculate(calculatorFromBmr.getHeight(),calculatorFromBmr.getBodyweight(),calculatorFromBmr.getAge()));
return "bmrform";
}
I METODA Z WALIDACJA, W KTÓREJ CZEGOŚ BRAKUJE...
@RequestMapping(value="bmrform", ,method = RequestMethod.POST)
public String saveResult(@Valid CalculatorFromBmr calculatorFromBmr, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
System.out.println("There were errors");
bindingResult.getAllErrors().forEach(error -> {
System.out.println(error.getObjectName() + " " + error.getDefaultMessage());
}
);
return "bmrform";
} else {
return "redirect:/bmr";
}
}