Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate HTML5 date format

I want to use the HTML5 date input field

<input type='date' name='customDate'>

So that other users can make use of the build-in datepicker from their browser.

I would like to check if the input is actually in date format. As I found here: Is there any way to change input type="date" format? there is no unique presentation format. For example, in Chrome the input of the date field is given in the form of dd.mm.yyyy and in Firefox 24 or IE 9/10 the date in the input field is presented as YYYY-MM-DD.

My first problem is, how do you tell the user in which format you want him to type in the date? In Firefox I would need something like

<label>Enter Date(YYYY-MM-DD)</label><input type='date' 
                                         name='customDate' placeholder='YYYY-MM-DD'>

But this would be wrong for Chrome.

Secondly, how can I check before submission if the current input is in the valid date format (of the browser)? I know that I could check with PHP after submit if the date format is given as YYYY-MM-DD, but how do you check it with JavaScript before submission?

like image 522
Adam Avatar asked Feb 02 '16 11:02

Adam


2 Answers

Use it like this:

<label>Enter Date(YYYY-MM-DD)</label>
<input type='date' name='customDate' placeholder='YYYY-MM-DD' pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" >

For all other HTML5 Dates Pattern Please visit this:

http://html5pattern.com/Dates

like image 146
Atif Tariq Avatar answered Sep 25 '22 11:09

Atif Tariq


I think the best way to validate HTML5 date format is to leave the job to the datepicker if one is available.

For instance, the native datepicker of chrome or ios5 does not allow wrong user date input. In chrome it even checks if the date does exists in a human calendar.

If the browser does not have native datepicker (like firefox), then this should be detected with Modernizer and one should use the jQuery UI datepicker. Here is a nice article that explains how to do this. Unfortunately, the jQuery datepicker does not check if the input is valid. However, one can set the dateType and constrainInput, but they dont check if the date actually exists, just if the syntax is correct. Note that the jquery validation plugin has troubles with the date attribut.

like image 1
Adam Avatar answered Sep 28 '22 11:09

Adam