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

Blazor Custom Validator无法传入变量文本 报CS0120如何实现多语言验证

能否通过属性向验证器类传动态值?

不能直接这么做。你的报错是C#特性本身的语法限制:所有应用在属性上的特性参数必须是编译时就能确定的常量,不能引用运行时才会赋值的实例属性(比如你组件的Parameter属性),所以你写的IsRequiredErrorText = order_by_RequiredErrorText不符合语法要求,会触发CS0120错误。

你可以通过以下两种方案实现多语言/动态错误消息的需求:

方案1:基于多语言资源文件实现国际化(推荐)

如果你的错误消息仅需要适配多语言,不需要组件外部动态传入,直接用.NET自带的资源文件体系即可:

  1. 项目中添加对应语言的资源文件,比如Resources.zh-CN.resx、Resources.en-US.resx,在文件内配置键值对,比如键OrderByRequired对应不同语言的错误文本
  2. 修改自定义验证特性,验证时根据当前语言读取对应文本:
public class CustomValidatorIsRequired : ValidationAttribute
{
    // 仅传资源键,属于编译时常量,符合特性参数要求
    public string ErrorMessageKey { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null || string.IsNullOrEmpty(value.ToString()))
        {
            // 自动读取当前线程UICulture对应的资源文本
            var errorMsg = Resources.ResourceManager.GetString(ErrorMessageKey);
            return new ValidationResult(errorMsg, new[] { validationContext.MemberName });
        }
        return ValidationResult.Success;
    }
}
  1. 使用时直接传资源键即可:
[CustomValidatorIsRequired(ErrorMessageKey = "OrderByRequired")] 
[Parameter] public string order_by_Text { get; set; } 

方案2:需要父组件动态传入错误文本的场景

如果确实需要父组件通过Parameter给验证器传自定义错误文本,就不要用静态的ValidationAttribute特性验证,改成组件内手动处理验证逻辑:

  1. 移除属性上的CustomValidatorIsRequired特性
  2. 在组件内订阅EditContext的字段变更事件,手动做验证:
[Parameter] public string order_by_RequiredErrorText { get; set; }
[Parameter] public string order_by_Text { get; set; }
[CascadingParameter] private EditContext EditContext { get; set; }
private ValidationMessageStore _validationStore;

protected override void OnInitialized()
{
    _validationStore = new ValidationMessageStore(EditContext);
    EditContext.OnFieldChanged += (sender, e) =>
    {
        if (e.FieldIdentifier.FieldName == nameof(order_by_Text))
        {
            // 清空当前字段的历史错误
            _validationStore.Clear(e.FieldIdentifier);
            if (string.IsNullOrEmpty(order_by_Text))
            {
                // 直接使用已经初始化完成的Parameter值作为错误消息
                _validationStore.Add(e.FieldIdentifier, order_by_RequiredErrorText);
            }
            EditContext.NotifyValidationStateChanged();
        }
    };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:45:01