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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With