加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用新的错误消息创建自定义MaxLength和Required验证,

发布时间:2020-12-16 02:02:52 所属栏目:百科 来源:网络整理
导读:[MaxLength(45,ErrorMessage = Translations.Attribute.MAX_LENGTH)][Required(ErrorMessage = Translations.Attribute.REQUIRED)] 如何使用默认翻译消息创建自定义Required和MaxLength验证.我可以简单地覆盖它并只更改errorMessage吗? 我只是想写 [MyMaxLe
[MaxLength(45,ErrorMessage = Translations.Attribute.MAX_LENGTH)]
[Required(ErrorMessage = Translations.Attribute.REQUIRED)]

如何使用默认翻译消息创建自定义Required和MaxLength验证.我可以简单地覆盖它并只更改errorMessage吗?

我只是想写

[MyMaxLength(45)]
[MyRequired]

已成立的解决方案:

public class MyRequiredAttribute : RequiredAttribute
    {
        public override string FormatErrorMessage(string name)
        {
            return string.Format("Polje {0} je obvezno",name);
        }
    }

解决方法

您应该能够从MaxLengthAttribute或您正在使用的任何其他属性派生…

public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = Translations.Attribute.MAX_LENGTH;
    }

    // other ctors/members as needed
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读