MVC .Net Core Model Validation - The value '' is invalid. Error

拥有回忆 提交于 2019-11-30 07:52:32

问题


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>

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


回答1:


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




回答2:


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.

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 and used getvalueordefault method when using it

public bool? IsCorporateAccount { get; set; }



回答3:


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




回答4:


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>


来源:https://stackoverflow.com/questions/43281345/mvc-net-core-model-validation-the-value-is-invalid-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!