2

In my model I've got a non-nullable DateTime field. I haven't made it a required field. When I leave the corresponding input in the view empty and check for the modelstate I see that the validation fails on this field. It says "Value cannot be empty". Now, I understand that simple values can't be null so they have to be assigned some value. I also understand that making this field nullable will solve the problem. But how can I catch the case when the attempted value is empty for a certain field (just like default model binding does) to show my custom error message instead of the generic one?

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206

1 Answers1

1
public class Person
{
    [DataType(DataType.DateTime)]
    [Required(ErrorMessage = 'show my custom error message instead of the generic one')]
    public DateTime StartDate{get;set;}
}

explicitly specify error messages as strings. Alternatively you can define them within resource files and optionally localize them depending on the language/culture of the incoming user.

Hasta Tamang
  • 2,205
  • 1
  • 18
  • 17
  • That's a possible solution but I'm more interested in catching that case manually. – Mikayil Abdullayev Dec 30 '15 at 08:21
  • Are you looking for custom validation attribute: http://stackoverflow.com/questions/16100300/asp-net-mvc-custom-validation-by-dataannotation – Hasta Tamang Dec 30 '15 at 08:24
  • In your controller method to you could do something like ModelState.AddModelError("StartDate", "Custom error message"); after performing your custom logic to catch a specific case. – Amanvir Mundra Dec 30 '15 at 08:27
  • @HastaPasta, if you look at the ModelState object in debug mode navigating down to the non-nullable simple field you'll find that there's a value called AttemptedValue with the value of `""` . That's what I want to catch. – Mikayil Abdullayev Dec 30 '15 at 08:30
  • It seems I have to implement my own Model Binder for what I want to achieve. Don't get me wrong, the solution you suggested works just fine, but I want to catch that case myself. – Mikayil Abdullayev Dec 30 '15 at 08:33