【问题标题】:Client-side validation for custom StringLength validation attribute自定义 StringLength 验证属性的客户端验证
【发布时间】:2015-03-26 06:15:48
【问题描述】:

我有以下自定义验证属性,它派生自 StringLengthAttribute:

public class StringLengthLocalizedAttribute : StringLengthAttribute
{
    public StringLengthLocalizedAttribute(int maximumLength) : base(maximumLength)
    {
        var translator = DependencyResolver.Current.GetService<ITranslator();
        var translatedValue = translator.Translate("MaxLengthTranslationKey", ErrorMessage);
        ErrorMessage = translatedValue.Replace("{MaxLength}", maximumLength.ToString());
    }
}

此自定义属性的唯一目的是本地化 ErrorMessage。问题是,当我在模型中使用它时,它不会生成任何客户端验证,但标准的 StringLength 属性会生成。

我看不出我的属性有什么不同 - 因为它派生自 StringLength 属性,所以我不应该实现任何额外的功能来让客户端验证正常工作?

【问题讨论】:

    标签: c# asp.net-mvc validation


    【解决方案1】:

    如果您查看 DataAnnotationsModelValidatorProvider 的源代码,您会在 BuildAttributeFactoriesDictionary 方法中看到为客户端验证注册了特定类型的属性 - 您创建了一个新类型,因此没有客户端验证。

    谢天谢地,这也有一个公共方法来添加你自己的适配器,并且在你给出的简单情况下很容易使用:

    首先,您需要一个适配器来提供客户端验证规则:

    public class MyStringLengthAdapter : DataAnnotationsModelValidator<MyStringLengthAttribute>
    {
        public MyStringLengthAdapter(ModelMetadata metadata, ControllerContext context, MyStringLengthAttribute attribute)
            : base(metadata, context, attribute)
        {
        }
    
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            return new[] { new ModelClientValidationStringLengthRule(ErrorMessage, Attribute.MinimumLength, Attribute.MaximumLength) };
        }
    }
    

    然后您需要在 Global.asax.cs 的 Application_Start 方法中注册它,如下所示:

    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof (MyStringLengthAttribute), typeof (MyStringLengthAdapter));
    

    【讨论】:

    • 嗯,这很尴尬...刚刚看到我在早期的一些验证工作中已经将我的其他自定义本地化属性映射到 Application_Start 中它们各自的适配器对应项。
    • 我可以补充一点,我什至不必创建自定义 MyStringLengthAdapter,因为我的属性中没有任何自定义验证逻辑。映射适配器就足够了:DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthLocalizedAttribute), typeof(StringLengthAttributeAdapter));
    猜你喜欢
    • 1970-01-01
    • 2012-03-06
    • 2011-09-09
    • 2013-11-12
    • 2014-03-27
    • 2014-11-03
    • 2011-06-12
    • 2017-12-13
    • 1970-01-01
    相关资源
    最近更新 更多