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

ASP.NET Core动态表单自定义默认验证错误消息方法咨询

解决方案

问题根源在于你的Units_Service是List<int>类型:当输入非数字内容时,ASP.NET Core会先触发模型绑定阶段的类型转换错误,框架直接返回默认的"The value 'a' is invalid"消息,此时你的RegularExpression验证逻辑还未执行(因为模型绑定未通过,不会进入数据注解验证环节)。

下面是两种可行的解决方法:

方法一:修改属性类型为string,通过正则验证后转换为int

将视图模型的属性类型改为List<string>,让模型绑定先成功,再触发正则验证显示自定义消息:

[RegularExpression("^[0-9]*$", ErrorMessage = "The value must be numeric")]
// 如果不允许空值,可额外添加[Required(ErrorMessage = "请输入数值")]
public List<string> Units_Service { get; set; }

在表单提交后的处理逻辑中,将字符串列表转换为int列表使用:

// 确保验证通过后再转换,避免格式错误
var numericUnits = model.Units_Service.Select(s => int.Parse(s)).ToList();
// 或用TryParse做安全处理
var numericUnits = new List<int>();
foreach (var s in model.Units_Service)
{
    if (int.TryParse(s, out int num))
    {
        numericUnits.Add(num);
    }
}

方法二:自定义模型绑定的类型转换错误消息

如果不想修改属性类型,可以直接替换框架默认的类型转换错误提示,让所有int类型绑定失败时显示自定义消息:
在Program.cs(ASP.NET Core 6及以上版本)中添加配置:

builder.Services.AddControllersWithViews()
    .AddMvcOptions(options =>
    {
        // 替换"值必须是数字"的默认提示
        options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(
            _ => "The value must be numeric");
    });

内容的提问来源于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.07 05:20:09