Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 289
TTCG Avatar asked Apr 07 '17 15:04

TTCG


People also ask

What is the use of ModelState IsValid in MVC?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.


1 Answers

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

like image 156
Denis Krasakov Avatar answered Sep 19 '22 04:09

Denis Krasakov