How to validate that user specified correct Date in ASP.NET MVC?
Is there any simple way to client (and server) side validate Date ?
My idea is to have 3 input fields for day, month and year. I'm using anotated model and AJAX validation scripts to client side validate the data. How can I do that with date ?
I can set something like day must be from Ran开发者_Go百科ge<1, 31> but still, if the month is february then value 31 is invalid...
http://forums.asp.net/p/1500029/3546376.aspx and http://www.dotnetspider.com/resources/17816-Javascript-date-validation.aspx.... may help u i hope. all the best
I agree with @bAN - the most user friendly way is to use a datepicker. Users with javascript disabled will have to write the dates manually into the textbox. You can also detect disabled javascript and do a fallback to a version without the datepicker in that case.
If you really want 3 input fields, you have a few options though. You need 3 properties on your model int day; int month; int year;
. When you receive the data from the client, you will have to do the validation manually by trying to create a DateTime
object. It will throw an exception if you specify an incorrect format:
try
{
var date = new DateTime(model.Year, model.Month, model.Day);
...
}
catch(ArgumentOutOfRangeException exception)
{
ModelState.AddModelError(...);
}
As a more pleasant user experience you can have 3 dropdowns instead. You can change the number of days depending on which month is selected and/or run validation at the client side.
A custom model binder seems like a good solution for this.
精彩评论