Far as I can tell, and that’s pretty far even though I do wonder if you can actually measure telling in distance, there isn’t a method directly used for validating a date in jquery. I find this rather odd. Not odd like how people keep watching Uwe Bol movies, more like odd that no one has tried to make a time machine to prevent them from ever appearing.
Anyways, bad movies… horrible movies… worst movies of all time aside, there is a date checking method, just not directly in jquery. It’s actually in the jquery.ui.datepicker.js file which is part of the UI files. Basically I grabbed that file and used the parseDate method on it coupled with a try catch. After all, a failure in the parseDate method throws an exception, and we don’t like those. No we don’t. (Which begs the question as why it throws an exception instead of just returning a null date.)
function isValidDate(controlName, format){ var isValid = true; try{ jQuery.datepicker.parseDate(format, jQuery('#' + controlName).val(), null); } catch(error){ isValid = false; } return isValid; }
Very simple, and it works. You could ask why I didn’t just roll my own date method, and then I would ask you how ambitious do you think I am? Then you would punch me because I answered your question with a question like a complete tool bag. Then I would cry. And THEN I would answer your original question. Fact is, I trust that the method created for the DatePicker is in fact well tested, otherwise the whole jquery thing just isn’t worth trusting seeing as it’s a part of their core library. And that I just refuse to believe.
This is great, thanks Sean! (& perfect timing for me, too 😉
FWIW: the datepicker validates “2/2/2”, so I added a quick regex before your try:
var val = $(‘#’ + controlName).val();
var regexp = /^d{1,2}/d{1,2}/d{4}$/;
if (!regexp.test(val)) {
isValid = false;
};
This is great, Sean, thanks!
FWIW- datepicker validates “2/2/2” so I added a regex before your “try…” :
var val = $(‘#’ + elemID).val();
var regexp = /^d{1,2}/d{1,2}/d{4}$/;
if (!regexp.test(val)) {
isValid = false;
};
Yeah, since 2/2/2 is a valid date, it will roll with it. Good catch.
Thanks so much for this helpful tutorial.
I dig your attitude as well as your humor. It’s much needed on this particular Friday.
Evik James
I aim to serve.
thanks
Great help.
Thanks!
For a generic date validation where you could pass the date format (java date formats) to this method, the regexp is a bad solution. since the method supports validating against a particular format, it should have thrown an exception –
What about 17/17/0000 ?
Throws exception. “Unexpected literal at position 2” (when using the ‘yy-mm-dd’ format).