MVC .Net Core 模型验证 - 值“"无效.错误

MVC .Net Core Model Validation - The value #39;#39; is invalid. Error(MVC .Net Core 模型验证 - 值“无效.错误)
本文介绍了MVC .Net Core 模型验证 - 值“"无效.错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'.

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

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.

我的模型

[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.

I put different ErrorMessage for both Required and DataType tag as shown in the above.

我的 html 视图

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

推荐答案

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

In order to make your Required attribute works you need to make field nullable:

public DateTime? AppointmentDate { get; set; }

Edit:还请注意,DataType 属性实际上不对字段执行验证.将 post 数据绑定到 model

Edit: also note that DataType attribute actually doesn't perform validation on field. MVC validate date when applying binding from post data to model

这篇关于MVC .Net Core 模型验证 - 值“"无效.错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)