Let's say you submit a date like '2015-06-31' which is invalid. Javascript will do the smart thing, really people
, and consider that date as '2015-07-01' if you create a Date object out of it.
Searching for a solution i came across the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
dtMonth = dtArray[3];
dtDay= dtArray[5];
dtYear = dtArray[1];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay> 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay> 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
From : http://stackoverflow.com/questions/18758772/how-do-i-validate-a-date-in-this-format-yyyy-mm-dd-using-jquery
It seems pretty complete and it has a special case to workaround the behavior at the start of this post.
As an alternative you could create a new Date object and compare
dtMonth and
dtDay and
dtYear to be the same as before.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
dtMonth = dtArray[3];
dtDay= dtArray[5];
dtYear = dtArray[1];
var date = new Date(txtDate);
return (date.getMonth()==(dtMonth-1) && date.getDate()==dtDay && date.getFullYear()==dtYear);
}
You can test it here - http://jsfiddle.net/EywSP/2282/
The month count being from 0 to 11 also makes perfect sense.
My next post will focus on odoo and how to implement a simple questionnaire framework for your clients.
Sem comentários:
Enviar um comentário