Regular Expression for Pattern Attribute in Form Field

MySQL databases accept dates in many different formats. For example, YY-MM-DD, YYYY:MM:DD, YYYYMMDD, and YYYY-MM-DD, among the myriad options for date formatting. (Y is for year, M is for month, and D is for day.)

Embracing HTML5’s pattern form attribute, which accepts a regular expression pattern, I wanted to accept dates from 0000-00-00 through 2015-12-31. The result is…

<input type="text" name="dob" id="dob" placeholder="YYYY-MM-DD" pattern="([0-1][0-9][0-9][0-9]|20[0-1][0-5])-(0[0-9]|1[0-2])-([0-2][0-9]|3[0-1])">

If a user enters a date in the wrong format, HTML5 browsers will complain:

[Screen capture of Chrome’s error message relating to a wrong date-based pattern match]
Screen capture of Chrome’s error message relating to a wrong date-based pattern match.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.