0

I have a simple ViewModel class in my asp.net mvc application.

public class DestinationViewModel
{
     [Display(Name = "Country")]
     [some validation attributes]
     public string CountryName { get; set; }

     [Display(Name = "Destination")]
     [some validation attributes]
     public string DestinationName { get; set; }

     public DateTime? DepartureDate { get; set; }

     public DateTime? ArrivalDate { get; set; }
}

When i pass data to controller my application shows validation errors on invalid departure and arrival date. But i donnt want such behavior. Is there any way(attribute) to disable validation only on DepartureDate and ArrivalDate fields?

2
  • 1
    What is the validation message? Invalid DateTime? Commented Oct 22, 2012 at 15:25
  • @jrummell Usual ASP.NET validation message: "The value '21321' is not valid for ArrivalDate." Commented Oct 22, 2012 at 15:29

2 Answers 2

2

The MVC data binder will attempt to convert which ever value you put in your input field to it's corresponding ViewModel type. In your scenario, you are passing "21321" which obviously isn't going to work as it's not valid Date/Time.

Either pass a valid DateTime string value or leave it empty (as the field is nullable).

Tip - It's usually a good idea from a users point of view to make date fields readonly and provide a date picker of some sort to avoid issues with manually entering valid date formats.

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

4 Comments

Sure i can write to input any value but users of my application do not so careful. And my PM too.
You can also try defining your own LooseDateTime type and then write a custom modelbinder for it. This gives you the maximum flexibility it sounds like you're looking for.
@Neir0 isn't the whole point of validation to make sure users carefully enter input values?
@Neir0 that's exactly my point, don't allow users to enter their own values for things as dates because if you ever changed format etc it would affect the end users.
1

If you want to write anything you want, then use string, not DateTime? or use one of this solutions:

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.