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

Blazor组件中如何获取MaxLengthAttribute值生成自定义验证错误消息?

解决Blazor中基于DataAnnotation生成自定义MaxLength错误消息的方法

要在Blazor的HandleSubmit函数里,根据字段的Display名称关联对应的MaxLengthAttribute并获取长度值,你可以通过反射实现,具体步骤和代码如下:

核心思路

  1. 通过反射获取模型类的属性信息
  2. 匹配目标字段的Display名称,找到对应的属性
  3. 从属性上提取MaxLengthAttribute的长度值
  4. 生成自定义错误消息

代码实现

假设你的模型类名为VehicleModel,在HandleSubmit函数中可以这样写:

// 需引用命名空间:
// using System.Reflection;
// using System.ComponentModel.DataAnnotations;

private void HandleSubmit()
{
    var modelType = typeof(VehicleModel);
    PropertyInfo? targetProperty = null;

    // 方式一:通过Display名称匹配属性(适合不知道属性名的场景)
    foreach (var prop in modelType.GetProperties())
    {
        var displayAttr = prop.GetCustomAttribute<DisplayAttribute>();
        if (displayAttr != null && displayAttr.Name == "Vehicle Number")
        {
            targetProperty = prop;
            break;
        }
    }

    // 方式二:直接通过属性名查找(更高效,推荐已知属性名时使用)
    // targetProperty = modelType.GetProperty(nameof(VehicleModel.TXT_VHCL_NUMBER));

    if (targetProperty != null)
    {
        var maxLengthAttr = targetProperty.GetCustomAttribute<MaxLengthAttribute>();
        if (maxLengthAttr != null)
        {
            // 生成自定义错误消息
            var customMsg = $"The 'Vehicle Number' is limited to {maxLengthAttr.Length} characters.";
            
            // 若要将消息添加到表单验证错误中,可使用EditContext:
            // EditContext.AddModelError(targetProperty.Name, customMsg);
        }
    }
}

注意事项

  • 必须引用System.Reflection命名空间,才能使用反射相关API
  • 如果你的组件使用了EditForm和EditContext,可以直接结合EditContext.Model获取当前模型实例,再进行反射操作
  • 直接通过属性名查找的效率远高于遍历Display名称,建议优先使用这种方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:42:35