2

Trying to add text with a style on error validation in a bootstrap form

This is part of the form:

<label th:text="#{name}"
        class="col-form-label col-form-label-sm"></label> 
<input
        type="text" class="form-control form-control-sm"
        th:field="*{name}" /> 
<span
        th:if="${#fields.hasErrors('name')}" th:errors="*{name}"
        th:class="invalid-feedback">Here there is an error</span>

I get the message on validation error, but without styles.

If I debug I see the class with the style:

<span class="invalid-feedback">Here there is an error</span>

I have tried with severals styles like help-block but no way.

I'm using bootstrap4.0.0-alpha.6

Any idea?

Thanks

davisoski
  • 727
  • 2
  • 14
  • 41
  • You can remove `th:` in `th:class`. You basicallly need to use `th:` when there's a variable involved and when you need Thymeleaf to evaluate it. – riddle_me_this Apr 10 '18 at 00:18
  • with or without th the class is not applied. Temporary resolved using inline style – davisoski Apr 10 '18 at 14:37

1 Answers1

4

In case you are still interested.

Bootstrap's current validation docs give you three approaches: client-side custom validation, browser defaults and server-side validation.

From your post I will assume you're using server side, meaning that you are sending the data to be validated in your server code for then showing the error fields when the form is re-rendered.

In that case, remember that for bootstrap's styles to kick in, a certain html structure is expected from your code, example:

<input th:field ="*{email}" type="email" class="form-control"
        th:classappend="${not #lists.isEmpty(#fields.errors('email'))} ? is-invalid"
        required>
<div class="invalid-feedback">
    <p th:each="error: ${#fields.errors('email')}" th:text="${error}">Invalid data</p>
</div>

(I believe a span tag will work too for <div class="invalid-feedback">)

That is a minimal necessary structure for the error styles to work. What happens:

  1. Initially, invalid-feedback is assigned display: none
  2. The form is submitted, if it has an error it'll be re-rendered and it's up to the developer to provide a mechanism which will include is-invalid in the class attribute of every <input class="form-control"/> with an error. In the previous code, th:classappend="${not #lists.isEmpty(#fields.errors('email'))} ? is-invalid" is responsible for that to happen. (I'm new to Spring and Thymeleaf, so there could be a neater code for this)
  3. Declaration .form-control.is-invalid~.invalid-feedback in _forms.scss will kick in and assign display: block to <div class="invalid-feedback">, thus showing each field's error message (s).

That should be enough to show the error (s) under each field and highlight them in red.

HIH

Scaramouche
  • 3,188
  • 2
  • 20
  • 46