1

I'm writing a training application to collect books on the following stack: Java/Spring/Thymeleaf.

I should input some values about books such as a book title and a book size (a number of pages).

Validation fields in dto class Book:

@NotEmpty
private String title;
@NotNull
@Digits(integer = 4, fraction = 0)
private Integer size;

The view file contains:

 <td>
    <input type="text" placeholder="book_title" th:field="*{title}">
    <p th:if="${#fields.hasErrors()} and *{title}==''">field title must not be empty</p>
</td>
<td>
    <input type="text" placeholder="size (page)" th:field="*{size}">
    <p th:if="${#fields.hasErrors()} and !${#size.matches('[0-9]{1,4}')}">field value must be digit and less than 4 signs</p>

It works properly: if the title field is not filled we can see the message. However, for the size field we expect 4 digits, but how to configure this regex correctly? !${#size.matches('[0-9]{1,4}')} in this way there is no warning message.

I have foung the simillar question Check if a string contains number or is numeric - Thymeleaf But I need to invert boolean condition and it dooes not work for my case

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
A user
  • 29
  • 1
  • 9

1 Answers1

1

You can check which field has errors in the Thymeleaf template when calling hasErrors() function.

Something like this:

<p th:if="${#fields.hasErrors('size')}">field value must be digit and less than 4 signs</p>

This way the error is shown only when the size field has errors and you don't need to use the regex to check its value.

Monitoria
  • 401
  • 2
  • 6