我正在尝试使用th:pattern
对于日期输入表单字段,如下所示使用 spring-mvc 的 thymeleaf 模板,但没有运气。还有其他人经历过类似的事情并有一些见解或替代方案吗?
我尝试了 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'
最佳答案
pattern
是 input
标记的 html5 属性。
pattern
使用 regex 验证 input
值。因此,您插入到 pattern
属性中的值应该是正确的正则表达式 模式。
如果您使用Thymeleaf的th:
前缀,模板处理器会尝试在Spiring的模型中找到适当的变量并将其插入作为属性的值。 Thymeleaf 正在使用 Spring EL 它的模板。
因此,由于使用了无效的 SpringEL 表达式,您的第一种方法是不正确的。
第二个解决方案看起来更好,type="date"
为您提供了您想要的,但有效 not for all browsers 。 ${classdate_format}
看起来是正确的表达式。要了解导致第二个错误的原因,需要更多代码。
无论如何,有什么理由为 pattern
属性使用 th:
前缀吗?仅当您想在服务器端动态创建正则表达式模式时才需要它。但在这种情况下,正则表达式模式非常简单,因此您可以使用不带 th:
的属性。要为您的情况编写正确的正则表达式,请参阅 this answer .
关于java - Thymeleaf <input> 日期出现 :pattern 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530018/