Rasto
Rasto

Reputation: 17774

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 Range<1, 31> but still, if the month is february then value 31 is invalid...

Upvotes: 1

Views: 1065

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

A custom model binder seems like a good solution for this.

Upvotes: 0

Yakimych
Yakimych

Reputation: 17752

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.

Upvotes: 1

Related Questions