As the title says I'm trying to display the errors in the HTML. The BindingResult contains the errors, that were found. The th:if="${#fields.hasAnyErrors()}"
returns false.
I'm not very experienced in any of this. I just combined some stuff I read on here. I don't quite know the difference between the BR and the Fields call. But I've seen, that the errors in the BR can be displayed in the HTML.
The validation is done by a custom validator. I think that might be the issue.
PostMapping function
@PostMapping ("/form")
public String processForm(@Valid RequestDummy rq, BindingResult br, Model m) {
buildForm(m);
m.addAttribute("request", rq);
if (br.hasErrors()) {
System.out.println("found error");
System.out.println(br.getFieldError("operator")); // only testing
System.out.println(br.getFieldError("booknew"));
return "form";
}
mgr.process(rq.toRequest());
if (rr.hasError()) displayError(m);
else insertResult(m);
rr.clear();
return "form";
}
Depending on the error I try to produce I get the following in the console. operator missing error:
found error
Field error in object 'requestDummy' on field 'operator': rejected value [none]; codes [operator.requestDummy.operator,operator.operator,operator.java.lang.String,operator]; arguments []; default message [Operator is not valid]
null
blank book error:
found error
null
Field error in object 'requestDummy' on field 'booknew': rejected value []; codes [booknewblank.requestDummy.booknew,booknewblank.booknew,booknewblank.java.lang.String,booknewblank]; arguments []; default message [Bookname can't be blank]
HTML piece
<!--Operator-->
<div class="form-group col-md-6">
<label for="idoperator">Operator</label>
<select class="form-control" name="operator" id="idoperator"
onchange="formupdate();" th:field="*{operator}">
<option disabled selected value="none">Select operator</option>
<option th:each="op : ${operators}"
th:text="${op.displayvalue()}"
th:value="${op}"></option>
</select>
<div th:if="${#fields.hasErrors('operator')}">
<p th:errors="${#fields.errors('operator')}"></p>
</div>
</div>
Custom Validator initialization
@Autowired
RequestValidator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
The @Bean just return a new RequestValidator.
Edit:
Additionally, I found out today, that certain commands from the website, make the program try to validate the RequestResult, Error (my own) or some other classes. I've checked multiple times, if I have any other annotation like @Valid
or @Validated
anywhere else, but there aren't any.
I always get an IllegalStateException: Invalid target for Validator
.