Error Messages
Learn how to add validation messages for validation errors in the form.
We'll cover the following...
Thymleaf has the #fields.hasErrors
method available in templates that allow us to check whether there is a validation error on a field.
Adding validation to firstName
We can apply this to the firstName
property, for example:
Press + to interact
<div class="sm:col-span-3"><label for="firstName" class="block text-sm font-medium text-gray-700"th:text="#{user.firstName}">First name</label><div class="mt-1 relative rounded-md shadow-sm"><input id="firstName"type="text"th:field="*{firstName}"class="shadow-sm block w-full sm:text-sm border-gray-300 rounded-md"th:classappend="${#fields.hasErrors('firstName')?'border-red-300 focus:border-red-300 focus:ring-red-500':'focus:ring-green-500 focus:border-green-500'}"><div th:if="${#fields.hasErrors('firstName')}"class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none"><svg class="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd"d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"clip-rule="evenodd"/></svg></div></div><p th:if="${#fields.hasErrors('firstName')}"class="mt-2 text-sm text-red-600" id="firstName-error">The first name cannot beempty.</p></div>
- An extra
<div>
is added that contains the SVG error icon. By usingth:if="${#fields.hasErrors('firs