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

TTCG picture TTCG · Apr 7, 2017 · Viewed 24.1k times · Source

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.

Answer

Denis Krasakov picture Denis Krasakov · Apr 7, 2017

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