如何检查字符串是否与thymeleaf中的regex匹配?

nhjlsmyf  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(268)

我正在编写一个培训应用程序来收集以下堆栈上的书籍:java/spring/thymeleaf。
我应该输入一些关于书的值,比如书名和书号(页数)。
dto类书中的验证字段:

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

视图文件包含:

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

它工作正常:如果 title 字段未填充,我们可以看到消息。然而,对于 size 字段我们期望4位数字,但如何正确配置这个正则表达式? !${#size.matches('[0-9]{1,4}')} 这样就没有警告信息了。
我有一个类似的问题检查字符串是否包含数字或是数字,但我需要反转布尔条件,它不适用于我的情况

jpfvwuh4

jpfvwuh41#

您可以在调用时检查thymeleaf模板中哪个字段有错误 hasErrors() 功能。
像这样:

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

这样,只有当 size 字段有错误,您不需要使用正则表达式来检查其值。

相关问题