41

I am trying to use Model Validation in MVC .Net Core and can't manage to replace this default error message 'The value '' is invalid'.

In theory, we can replace our own custom error message by using ErrorMessage Annotation in the Model. But I couldn't find a way to make this one work.

My Model

[Required(ErrorMessage = "Date Required")]
[DataType(DataType.Date, ErrorMessage = "Invalid Date Format")]                
[Display(Name = "Appointment Date")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime AppointmentDate { get; set; }

I put different ErrorMessage for both Required and DataType tag as shown in the above.

My html view

    <div class="col-md-2">
        <input class="form-control" asp-for="AppointmentDate">
        <span asp-validation-for="AppointmentDate" class="text-danger"></span>
    </div>

enter image description here

Could you please help me how I could get that error message replaced? Thanks.

TTCG
  • 8,805
  • 31
  • 93
  • 141
  • did you [check this](http://stackoverflow.com/questions/1538873/how-to-replace-the-default-modelstate-error-message-in-asp-net-mvc-2)? It might be what you are looking for – Polynomial Proton Apr 07 '17 at 15:05
  • Thanks but not that one. It's to replace an error message in another language like Spanish or Italian, etc. – TTCG Apr 07 '17 at 17:34

8 Answers8

54

In order to make your Required attribute works you need to make field nullable:

public DateTime? AppointmentDate { get; set; }

Edit: also note that DataType attribute actually doesn't perform validation on field. MVC validate date when applying binding from post data to model

Denis Krasakov
  • 1,498
  • 2
  • 13
  • 17
  • 1
    I'm getting the same problem, however, the only fields I have `[Required]` on are strings. And, I have the same Controller action for both adding and editing an entity. When editing, it works fine (before I do anything in the controller, i check `ModelState`), but trips this when adding a new entity. Everything is the exact same on the entity – MikeT Feb 01 '18 at 16:13
  • 1
    I had the same problem, the difference is that my property has Guid type. Make it nullable solved the problem. – Pedro Galinatti Apr 03 '20 at 01:41
14

After .NET Core 3 validation system changed. Non-nullable parameters are treated as if they had a [Required] attribute. You get client side validation even if you don't apply the [Required] attribute. Client side JQuery validation accepts empty strings fields but once sent to server the same field will get the invalid result. The value '' is invalid is the default error message for server side validation. According to asp.net docs by using a [Required] attribute you can override this message but it does not apply to empty fields. Unfortunately this feature generates empty string values ("") for hidden input fields that reference non-nullable int properties (i.e @Html.Hiddenfor(m=>m.id) would generate "" for the html element.) So out of all the options provided in asp.net docs the safest one is making the property nullable. another good option is changing .NET default message to something else

services.AddRazorPages()
    .AddMvcOptions(options =>
    {
        options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(
            _ => "The field is required.");
    });

You can read more about this here.

Hamed
  • 356
  • 2
  • 9
6

Having the same problem but cannot detect the problem. I checked the object in debug mode to see if is there any way to see which property fails the model state.

Debug mode view of the modelstate object

Then I see the which one fails model. That is a boolean value which maps to a checkbox

Weird part is "this is not a Required field"!

I added a question mark to make it nullable and used GetValueOrDefault method when using it

public bool? IsCorporateAccount { get; set; }
Ozan BAYRAM
  • 2,780
  • 1
  • 28
  • 35
1

In some case the validation summary can be the cause: Change the "All" for "ModelOnly":

<div asp-validation-summary="All" class="text-danger"></div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
Tidoy007
  • 79
  • 7
0

My issue was that in the Create Action, I'd return the View without newing up an Entity, which, when I changed that, i.e. Return View(new MyEntity()); it fixed the issue

MikeT
  • 2,530
  • 25
  • 36
0

My specific problem had to do with select option validation showing a similar message instead of my custom message from the model. In addition to the answer about making the validated property nullable, double check the actual value in the DOM element. My problem was solved by adding nullability and an empty string as the value in the default option which is supposed to be an int.

<select asp-for="@Model.Thing" asp-items="Model.Things"
    <option value="" selected>Please select a Thing</option>
</select>
<span asp-validation-for="@Model.Thing" class="text-danger"></span>
tnJed
  • 838
  • 9
  • 12
0

In my scenario I was getting a validation error on my 'NeedToPrint' property for my model. I had to make sure that I specified a VALUE in my cshtml file like this:

 <button type="submit" name="NeedToPrint" value="false" class="btn btn-default" >Submit</button>
Louis Cribbins
  • 121
  • 1
  • 2
0

In the "Get" Action, I instantiated the object and passed it to the view as the model, even I don't do anything with it, but it seems now .Net Core wants it all perfect and clean, can't use "old ways" using "defaults". enter image description here

Nestor
  • 1,969
  • 4
  • 25
  • 30