RegEx Date Validation for M/D/YYYY and MM/DD/YYYY (InfoPath)

manh2244 picture manh2244 · Apr 11, 2013 · Viewed 9.2k times · Source

I'm looking for some RegEx for a custom pattern validation for a date field in InfoPath 2010. The accepted date format is m/d/yyyy or mm/dd/yyyy.

Attempt 1: (\d{1,2})/(\d{1,2})/(\d{4})

Attempt 2: (0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\d\d)

Had better luck with attempt 1, and not much at all with attempt 2.

Answer

David Clarke picture David Clarke · May 9, 2013

I've been having some date and time validation issues with InfoPath 2010 and regex pattern matching can be a useful approach. A basic regex for validating m/d/yyyy (without catering for the specific days in a month and allowing for '0' prefix to month or day) would be something like the following (untested):

(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/\d{4}

For something more sophisticated you could have a look at this SO answer.

However, in InfoPath the format of the date displayed can be completely different to the internal format and it is this internal format that your regex needs to match. If you drop a calculated field on your form and set it to the date field you want to validate you will see something like:

2013-05-08T12:13:14

So a regular expression (again ignoring specific days per month) required to validate the date component of this is:

\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])

But this won't match against the example date because it doesn't account for the time portion following the "T". So the trick is to use an expression to perform the match against the date substring only, e.g. in my case the following works:

not(xdUtil:Match(substring-before(dfs:dataFields/my:SharePointListItem_RW/my:DateCreated, "T"), "\d{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"))