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:
- Initially,
invalid-feedback
is assigned display: none
- 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)
- 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