views:

31

answers:

3

Hello!

I have a date in the format YYMMDD. Is there anyway I can validate it in JavaScript? By validation I don't mean easier things like length, characters etc but rather if the date exists in real life.

I'm hoping there is a faster / better way than breaking it in 3 chunks of 2 characters and checking each individually.

Thank you.

+2  A: 

try to convert it to a date and if it fails, you get the dreaded NaN then you know it is not a valid date string? Not Pretty but it should work

var myDate = new Date(dateString);
// should write out NaN
document.write("Date : " + myDate);

You date string would have to be in a valid format for javascript I don't think what you have in your question YYMMDD is supported

Aaron Saunders
That's a good idea and beats validating each chunk. I can get the missing YY to make it an YYYYMMDD format. I'll give it a go and let you know. Thank you.
Francisc
+1  A: 

The format YYMMDD is not supported by Javascript Date.parse so you have to do some processing of it like breaking it in parts.

I would suggest building a function that splits it in 3 2 char strings and then builds an american style date

MM/DD/YY and try to parse that with Date.parse.

If it returns anything but NaN then its a valid date.

David Mårtensson
Thank you, David.
Francisc
+1  A: 

The Date parser in JavaScript is pretty useless. The actual formats it accepts vary greatly across browsers; the only formats guaranteed to work by the ECMAScript standard are whatever formats the implementation's toString and toUTCString methods produce. In ECMAScript Fifth Edition you will also get ISO-8166 format, which is nearer to your format but still not quite.

So, the best solution is usually to parse it yourself.

var y= parseInt(s.slice(0, 2), 10)+2000;
var m= parseInt(s.slice(2, 4), 10)-1;
var d= parseInt(s.slice(4, 6), 10);
var date= new Date(Date.UTC(y, m, d));

Now you've got a Date object representing the input date in UTC. But that's not enough, because the Date constructor allows bogus months like 13 or days like 40, wrapping around. So to check the given day was a real day, convert back to year/month/day and compare:

var valid= date.getUTCFullYear()===y && d.getUTCMonth()===m && d.getUTCDate()===d;
bobince