How can I change the error message for implicitly required properties in the view model?

I have properties declared in my view model:

[Required(ErrorMessage = "The Date field is required for Start.")] [Display(Name = "Start")] public DateTime DateStart { get; set; } 

However, I still get the default value. An error message is required in the Start field. I assume this is because implicit DateTime implicitly required, and the Required attribute is ignored. Is there a way to customize my error message for these specific properties, in addition to making them nullable?

+4
source share
2 answers

You are right, your problem is that your property cannot be zero. For attributes with invalid properties, the Required attribute does not make sense. If StartDate is not present, validation does not match your Required attribute and is not performed in the previous step. If you want to receive ErrorMessage , you should Application:

 [Required(ErrorMessage = "The Date field is required for Start.")] [Display(Name = "Start")] public DateTime? DateStart { get; set; } 

You cannot configure ErrorMessage for non-zero types that have a null value for model binding because it is heavily encoded within MVC.

+2
source

I started by updating a new test project in MVC 4 and created a test model

  public class TestModel { [Required(ErrorMessage = "The Date field is required for Start.")] [Display(Name = "Start")] public DateTime DateStart { get; set; } } 

Then in my model I just got the following:

 @using(Html.BeginForm()){ @Html.ValidationMessageFor(a => a.DateStart); @Html.TextBoxFor(a => a.DateStart) <input type="submit" value="add"/> } 

When I delete the clear text box and click submit, I get a customized error message instead of the default value.

 The Date field is required for Start. 

This makes sense to me, imagine if this is a multilingual application, you definitely need to set up an error message for this country. A rocket scientist does not need to realize the need for a personalized message. And I would expect the MVC team to be covered.

0
source

All Articles