I'm trying to build a validator that will work with .NET's DefaultModelBinder of using DateTime.Parse to convert a string from the form post to a DateTime. I don't want to have to wait until a date has been posted to the server for it to realize it was a bad date.
Currently jquery.validate uses the following code to validate date fields:
// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function(value, element) {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
However, due to Javascript's terrible Date parser, this:
275481/69/100089
Will evaluate as valid, to Sep. 12, 275760.
While on the other hand, this:
11-19-2013
Will evaluate as invalid.
Of course, I understand that C#'s DateTime.Parse() takes things like culture (localization) and leap year into account, and I could live with assuming a fixed (US) culture, and allowing "02-29-2013" on the client and kick it out at the server (ideally not, but it's acceptable).
But I can't believe someone hasn't put together a better date validator to work with C#'s DateTime.Parse() logic.
Maybe someone has, I just haven't found it -- which is why I'm posting here.
And I know I have several ways to go about this -- from incredibly simple (less accurate) to incredibly complex (more accurate), but I'm hoping someone has already gone down this road and found the sweet spot.
Datejs seems pretty robust to me. Its parse function supports over 150 cultures:
Date.parse("February 20th 1973")
And in case you need to parse a date string that is not valid in the current culture you can use the parseExact function:
// The Date of 15-Oct-2004
Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]);
In all honesty, your best bet is to perform an AJAX hit, and ask your ASP.net web-server to parse the string and return a Javascript date.
Javascript libraries easily get confused with different locales, e.g.:
GET /ParseDate.ashx?dateStaring=06/01/34 4:53:05 غ.و&locale=ar-SA
Which gets really complicated because:
"6/1/34" = November 19, 2012
The .NET framework, with Windows behind it, has support for a lot of different locales.
Instead of trying to find two Datetime implementations (one for JS and another for C#) that have similar validation and parsing, have you considered having the client 1)use its own library to validate the date and 2)parse and reformat the date to a C# friendly format?
This would allow you to use DateJS to get a very flexible front end for date inputs, make it easier to deal with the client side culture, and let your server side deal with a fixed format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With