Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...