You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义.NET Framework默认验证错误消息的字段显示名

问题描述

我在视图模型中有如下代码:

public DateTime? Activation_Date { get; set; }
public DateTime? Deactivation_Date { get; set; }

当在表单中输入日期为"abc"并点击保存时,收到的验证错误是:

The value 'abc' is not valid for Activation_Date.

我希望把错误消息里的Activation_Date改成"Activation Date"(去掉下划线),让错误消息显示为:

The value 'abc' is not valid for Activation Date.

视图中显示错误消息的代码是:

@Html.ValidationMessageFor(s => s.Activation_Date)
实现方法

这里有几种简单可行的方案,按推荐优先级排序:

1. 使用[Display]特性(推荐)

直接在视图模型的属性上添加[Display]特性,指定友好的显示名称。MVC的默认验证机制会自动使用这个名称替换错误消息里的字段名,无需修改视图代码。

修改后的模型代码:

using System.ComponentModel.DataAnnotations;

public class YourViewModel
{
    [Display(Name = "Activation Date")]
    public DateTime? Activation_Date { get; set; }

    [Display(Name = "Deactivation Date")]
    public DateTime? Deactivation_Date { get; set; }
}

提交无效日期时,错误消息会自动显示为目标格式,视图里的@Html.ValidationMessageFor不需要做任何改动。

2. 直接在ValidationMessageFor中指定错误消息

如果只需要针对单个字段临时修改,可以在视图的ValidationMessageFor方法里手动指定错误消息模板,把字段名替换为友好名称:

@Html.ValidationMessageFor(s => s.Activation_Date, "The value '{0}' is not valid for Activation Date.")

这种方法适合个别字段的特殊需求,但如果有多个字段需要修改,重复写模板会比较繁琐。

3. 自定义元数据提供器(适合批量处理)

如果有大量带下划线的字段需要统一替换为空格格式的名称,可以自定义一个元数据提供器,自动把属性名里的下划线替换成空格,无需逐个添加[Display]特性。

示例代码(在Global.asax或Startup类中注册):

using System.Web.Mvc;

public class CustomDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(
        IEnumerable<Attribute> attributes,
        Type containerType,
        Func<object> modelAccessor,
        Type modelType,
        string propertyName)
    {
        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
        
        // 未指定Display.Name时,自动替换下划线为空格
        if (string.IsNullOrEmpty(metadata.DisplayName) && !string.IsNullOrEmpty(propertyName))
        {
            metadata.DisplayName = propertyName.Replace("_", " ");
        }
        
        return metadata;
    }
}

// 注册元数据提供器(在Application_Start中)
ModelMetadataProviders.Current = new CustomDataAnnotationsModelMetadataProvider();

这种方法一劳永逸,所有未指定[Display]特性的属性都会自动把下划线替换成空格作为显示名称。


内容的提问来源于stack exchange,提问作者Fokwa Best

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:42:33