MVC .Net核心模型验证-值“"无效.错误 [英] MVC .Net Core Model Validation - The value '' is invalid. Error

查看:268
本文介绍了MVC .Net核心模型验证-值“"无效.错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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'.

从理论上讲,我们可以通过在模型中使用ErrorMessage注释来替换自己的自定义错误消息.但是我找不到一种方法来使这一工作有效.

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

编辑:还请注意,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核心模型验证-值“"无效.错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆