c# - 自定义 StringLength 验证属性的客户端验证

标签 c# asp.net-mvc validation

我有以下自定义验证属性,它派生自 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 属性,所以我不应该实现任何额外的功能来使客户端验证正常工作?

最佳答案

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

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

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

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));

关于c# - 自定义 StringLength 验证属性的客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28173753/

相关文章:

c# - 按日期排序 asp.net MVC 5

python - 如何在 django 中为继承的模型属性创建通用模型表单字段验证器?

css - 模仿 HTML5 表单验证默认样式

c# - 通用关系到复合 C# 对象映射器

c# - 以一种形式处理 2 个提交按钮

Html.Raw 改变整个页面的样式

php - 如何在 CakePHP 中读取 "Validate"人名?

c# - 用泛型对象初始化非泛型对象

c# - 合并 2 个数组以使元素以均匀间隔互锁的最快算法

c# - 检测字符串是否包含大写字符