gpt4 book ai didi

c# - MVC .Net Core 模型验证 - 值 '' 无效。错误

转载 作者:可可西里 更新时间:2023-11-01 03:08:50 26 4
gpt4 key购买 nike

我正在尝试在 MVC .Net Core 中使用模型验证,但无法设法替换此默认错误消息“值”无效。

理论上,我们可以通过在Model中使用ErrorMessage注解来替换自己自定义的错误信息。但我找不到一种方法来实现这一点。

我的模型

[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; }

我为 RequiredDataType 标签添加了不同的 ErrorMessage,如上所示。

我的 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

能否请您帮助我如何替换该错误消息?谢谢。

最佳答案

为了使您的 Required 属性起作用,您需要使字段可为空:

public DateTime? AppointmentDate { get; set; }

编辑:另请注意,DataType 属性实际上不对字段执行验证。将 post 数据绑定(bind)到 model

时 MVC 验证日期

关于c# - MVC .Net Core 模型验证 - 值 '' 无效。错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43281345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com