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

如何在@Html.ValidationMessageFor客户端验证消息中显示当前输入字段长度

实现方案

你之前的自定义属性仅对服务端验证生效,是因为客户端的长度验证逻辑由jquery.validate.unobtrusive独立处理,没有对应实现动态插入当前输入长度的逻辑,按以下步骤修改即可实现需求:

步骤1:调整自定义验证规则命名(避免和默认规则冲突)

修改MaxLengthWithLengthMessageValidator类中的ValidationType取值,使用独立命名避免覆盖原生maxlength规则:

public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = this._errorMessage,
        // 改为自定义规则名
        ValidationType = "maxlengthwithcount"
    };
    rule.ValidationParameters.Add("max", _attribute.Length);
    yield return rule;
}

步骤2:注册自定义验证适配器

在项目的Global.asax.cs的Application_Start方法中添加如下代码,注册自定义验证器的映射关系:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthWithLengthMessageAttribute), typeof(MaxLengthWithLengthMessageValidator));

步骤3:添加客户端自定义验证逻辑

在页面引入的验证JS(jquery.validate.js、jquery.validate.unobtrusive.js)之后,添加如下JS代码,实现客户端动态计算当前长度、替换错误消息占位符的逻辑:

// 注册自定义长度验证方法
$.validator.addMethod('maxlengthwithcount', function (value, element, maxLength) {
    const currentLength = value ? value.length : 0;
    return this.optional(element) || currentLength <= maxLength;
});

// 适配Unobtrusive验证规则
$.validator.unobtrusive.adapters.add('maxlengthwithcount', ['max'], function (options) {
    options.rules['maxlengthwithcount'] = parseInt(options.params.max);
    // 动态生成带当前长度的错误消息
    options.messages['maxlengthwithcount'] = function () {
        const currentLength = options.element.value ? options.element.value.length : 0;
        return options.message.replace('#1', options.params.max).replace('#2', currentLength);
    };
});

步骤4:替换模型的验证特性

将模型中原有的[MaxLength(500)]替换为自定义特性即可:

[Display(Name = nameof(Global.Opis), ResourceType = typeof(Global))]
[Required]
[MaxLengthWithLengthMessage(500)]
public string Opis { get; set; }

如果需要调整服务端返回的错误消息格式,同步修改MaxLengthWithLengthMessageAttribute中IsValid方法的消息拼接逻辑即可,保证前后端提示一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:06:04