java - Thymeleaf <input> 日期出现 :pattern 错误

标签 java spring-mvc thymeleaf

我正在尝试使用th:pattern对于日期输入表单字段,如下所示使用 spring-mvcthymeleaf 模板,但没有运气。还有其他人经历过类似的事情并有一些见解或替代方案吗?

我尝试了 1。对模式进行硬编码

<input type="text" th:pattern="MM/dd/yyyy" th:field="*{classDate}"/>

收到错误:

Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "MM/dd/yyyy" 

还有 2。在java代码中设置模式供模板使用

<input type="date" th:pattern="${classdate_format}" th:field="*{classDate}"/>

收到错误:

Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring3.processor.attr.SpringInputGeneralFieldAttrProcessor'

最佳答案

patterninput 标记的 html5 属性。

pattern 使用 regex 验证 input。因此,您插入到 pattern 属性中的值应该是正确的正则表达式 模式。

如果您使用Thymeleafth:前缀,模板处理器会尝试在Spiring的模型中找到适当的变量并将其插入作为属性的值。 Thymeleaf 正在使用 Spring EL 它的模板。

因此,由于使用了无效的 SpringEL 表达式,您的第一种方法是不正确的。

第二个解决方案看起来更好,type="date" 为您提供了您想要的,但有效 not for all browsers${classdate_format} 看起来是正确的表达式。要了解导致第二个错误的原因,需要更多代码。

无论如何,有什么理由为 pattern 属性使用 th: 前缀吗?仅当您想在服务器端动态创建正则表达式模式时才需要它。但在这种情况下,正则表达式模式非常简单,因此您可以使用不带 th: 的属性。要为您的情况编写正确的正则表达式,请参阅 this answer .

关于java - Thymeleaf &lt;input&gt; 日期出现 :pattern 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530018/

相关文章:

java - 使用 Windows Builder 创建逻辑 GUI 组件组

java - Java 中的对象实例化是否有每个方法的成本?

java - Hibernate将数据保存到数据库SQLException

java - Thymeleaf Spring 环 n 项目

edit - 编辑时选择了多个 thymeleaf

java - Spring Boot with Camel 无法加载应用程序上下文

java - 在描述中给出的场景中如何暂停程序执行?

hibernate - 未知枚举常量 javax.persistence.CascadeType.DETACH

java - ModelAndView对象未返回到jsp

spring - 使用 Spring JPA PagingAndSortingRepository 和 thymeleaf 进行分页