Home > OS >  Implement field validation via Thymeleaf (migrate from Freemarker to Thymeleaf)
Implement field validation via Thymeleaf (migrate from Freemarker to Thymeleaf)

Time:11-09

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

CodePudding user response:

You can use thymeleaf classappend th:classappend like this:

<input type="text" name="firstName" id="inputFirstName" th:classappend="${condition} ? conditionTrueClass : conditionFalseClass "/>

please look at this answer.

CodePudding user response:

You will need to use a conditional statement in your class to evaluate whether it should use an "error class"

Example:

<p  th:if="${#fields.hasErrors('age')}" th:class="${#fields.hasErrors('age')}? error">Invalid Age</p>

<style>
    .error {
        color: red;
    }
</style>

Another Thymeleaf attribute th:errors gives us the ability to display all errors on the specified selector, say email:

<div>
    <label for="email">Email</label> <input type="text" th:field="*{email}" />
    <p th:if="${#fields.hasErrors('email')}" th:errorclass="error" th:errors="*{email}" />
</div>

Reference: https://www.baeldung.com/spring-thymeleaf-error-messages

  • Related