1

I'm trying to use th:pattern for date input form field like following for a thymeleaf template using spring-mvc but without luck. Anybody else experienced similar thing and has some insight or alternative?

I tried 1. hard-coding the pattern

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

received Error:

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

And 2. setting pattern in java code for template to use

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

received Error:

Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring3.processor.attr.SpringInputGeneralFieldAttrProcessor'
Maxim Kolesnikov
  • 5,075
  • 6
  • 38
  • 68
jay
  • 125
  • 2
  • 9

1 Answers1

2

pattern is html5 attribute of input tag.

pattern validates an input value using regex. So that value, which you inserts into pattern attribute should be correct regex pattern.

If you are using Thymeleaf's th: prefix, template processor trying to find appropriate variable in Spiring's model and insert it as a value of attribute. Thymeleaf is using Spring EL for it's templates.

So your first approach is incorrect because of using invalid SpringEL expression.

The second solution looks better, type="date" gives you exactly what you want, but works not for all browsers. ${classdate_format} looks like correct expression. To understand what causes the second error more code needed.

Anyway is there any reason to use th: prefix for pattern attribute? It needed only if you want to create regex pattern dynamically at server side. But in this case regex pattern is pretty straightforward, so you can use attribute without th:. To write correct regex for your case please refer to this answer.

Community
  • 1
  • 1
Maxim Kolesnikov
  • 5,075
  • 6
  • 38
  • 68