4

I have properties declared in my view model like:

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

However, I am still getting a default The Start field is required error message. I assume this is because a non-nullable DateTime is implicitly required, and the Required attribute is ignored. Is there a way to customise my error message for these specific properties, besides making them nullable?

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • 1
    possible dublicate:http://stackoverflow.com/questions/6214066/how-to-change-default-validation-error-message-in-asp-net-mvc – AliRıza Adıyahşi Nov 29 '12 at 09:55
  • @AliRızaAdıyahşi That answer describes a global message change. I only want to change it for specific properties. I have updated the question. – ProfK Nov 29 '12 at 10:06
  • no for specific values it is not possible to change it. However you can supply a format string with holes to be filled with the display nam of the field...se my answer – Francesco Abbruzzese Dec 05 '12 at 16:28

2 Answers2

2

You right, your problem is that your property is not nullable. For not nullable properties attribute Required is meaningless. When there is no StartDate value, validation is not go to your Required attribute and fails on previous step. If you want to get your ErrorMessage you should use:

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

You cannot customize ErrorMessage for nonullable types that get null on modelbinding, cause it is hardcoded deep in MVC framework.

Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38
0

I've started with refresh new test project in MVC 4 and create 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 have this:

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

When I remove clean the text box and hit submit, I am getting the customized error message instead of the default.

The Date field is required for Start.

This make sense to me, imagine if this is a multilingual application, you will definitely need to customize the error message for that country. It doesn't take a rocket scientist to realise the need for customized message. And I would expect MVC team have that covered.

Jack
  • 2,600
  • 23
  • 29
  • @ProfK The exact message is "The Date field is required for Start." Let me know if you need a screenshot and the test solution I've create. – Jack Dec 06 '12 at 23:49