I'm developing one little Spring Boot App with user login and registration. I want to implement my own registration system with field validation. For validation I use my own implementation of org.springframework.validation.Validator
in controller. Vaidator catches all errors from bindingResult
in controller and send it to frontend in model
field:
@PostMapping("/registration")
public String signUpUser(User userForm, BindingResult bindingResult,
Model model) {
validator.validate(userForm, bindingResult);
if(bindingResult.hasErrors()) {
Map<String, String> errors = ControllerUtils.getFieldErrors(bindingResult);
model.mergeAttributes(errors);
return "registration";
}
return "registration";
If there will be any validation errors, Map<String, String> errors
will hold all that erorrs. For example, if user while registration won't fill field firstName
map will hold object like: "firstNameError" -> "Please, fill the field"
, and so on.
In my previous project I've used Freemarker as template engine and on frontend side code of some element were looking like that:
<label for="inputFirstName" class="sr-only">First Name</label>
<input type="text" name="firstName" id="inputFirstName"
class="form-control ${(firstNameError??)?string('is-invalid','')}"
placeholder="First Name" required autofocus>
<div class="text-left invalid-feedback m-1 ml-1">
<#if (firstNameError)??>
${firstNameError}
</#if>
</div>
So when I had an error with user's first name - my input changed class to class="form control is-invalid"
and it highlight field with errors, after that it displays an error message in div
Now I use Thymeleaf as a template engine. To display text of error I use
<div th:if="${firstNameError}" class="invalid-feedback">
<a th:text="${firstNameError}"></a>
</div>
But how can I change dynamicaly class
of <input...
to highlight fiend with errors?
Thank you!