1

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...

4
  • 3
    Why don't you use a javascript datepicker? like the jquery's one? Commented Mar 18, 2011 at 7:07
  • That seems to be reasonable suggestion. I spent few last hours looking for some that would satisfy all my needs(jQuery one is not the case)... Commented Mar 18, 2011 at 8:37
  • And what are your needs? Commented Mar 18, 2011 at 8:44
  • @bAN jQuery is great except I would prefer some picker that consist of 3 fields: for day, month and year. Sometimes users do not like to bother with UI drop down but they rather write it. In such case formating is never clear to user - is it delimited by / or space ? Or even '\'? And 3 fields with labels are clear to understand and so usable even when javascript is off. Commented Mar 18, 2011 at 8:49

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.