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?

Neir0
  • 12,849
  • 28
  • 83
  • 139

2 Answers2

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.

James
  • 80,725
  • 18
  • 167
  • 237
  • Sure i can write to input any value but users of my application do not so careful. And my PM too. – Neir0 Oct 22 '12 at 15:43
  • 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. – Mike Richter Oct 22 '12 at 16:20
  • 1
    @Neir0 isn't the whole point of validation to make sure users carefully enter input values? – jrummell Oct 22 '12 at 16:21
  • @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. – James Oct 22 '12 at 19:58
1

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

Community
  • 1
  • 1
webdeveloper
  • 17,174
  • 3
  • 48
  • 47