使用 AttributeTargets.Class 对自定义 ValidationAttribute 进行客户端验证

发布于 2024-11-03 18:08:40 字数 1342 浏览 2 评论 0原文

是否可以为类范围内使用的自定义 ValidationAttribute 实现客户端验证?例如我的 MaxLengthGlobal,它应该确保所有输入字段的全局最大限制。

[AttributeUsage(AttributeTargets.Class)]
public class MaxLengthGlobalAttribute : ValidationAttribute, IClientValidatable
{
    public int MaximumLength
    {
        get;
        private set;
    }

    public MaxLengthGlobalAttribute(int maximumLength)
    {
        this.MaximumLength = maximumLength;
    }

    public override bool IsValid(object value)
    {
        var properties = TypeDescriptor.GetProperties(value);

        foreach (PropertyDescriptor property in properties)
        {
            var stringValue = property.GetValue(value) as string;

            if (stringValue != null && (stringValue.Length > this.MaximumLength))
            {
                return false;
            }
        }

        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {       
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = this.FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "maxlengthglobal",
        };

        rule.ValidationParameters.Add("maxlength", this.MaximumLength);         
        yield return rule;
    }
}

谢谢。

Is it possible to implement client-site validation for custom ValidationAttribute, which is used in Class scope? For example my MaxLengthGlobal, which should assure global max limit for all input fields.

[AttributeUsage(AttributeTargets.Class)]
public class MaxLengthGlobalAttribute : ValidationAttribute, IClientValidatable
{
    public int MaximumLength
    {
        get;
        private set;
    }

    public MaxLengthGlobalAttribute(int maximumLength)
    {
        this.MaximumLength = maximumLength;
    }

    public override bool IsValid(object value)
    {
        var properties = TypeDescriptor.GetProperties(value);

        foreach (PropertyDescriptor property in properties)
        {
            var stringValue = property.GetValue(value) as string;

            if (stringValue != null && (stringValue.Length > this.MaximumLength))
            {
                return false;
            }
        }

        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {       
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = this.FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "maxlengthglobal",
        };

        rule.ValidationParameters.Add("maxlength", this.MaximumLength);         
        yield return rule;
    }
}

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仙女山的月亮 2024-11-10 18:08:40

我在寻找同一问题的解决方案时找到了这个答案,并提出了解决方法。

使用 2 个而不是 1 个 ValidationAttribute:

1.) ServerValidationAttribute 将位于类上,并且不会实现 IClientValidatable。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MyCustomServerValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // remember to cast to the class type, not property type
        // ... return true or false
    }
}

2.) ClientValidationAttribute 将位于字段/属性上,并将实现 IClientValidatable,但 IsValid 重写始终返回 true。

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, 
    AllowMultiple = false, Inherited = true)]
public class MyCustomClientValidationAttribute : ValidationAttribute, 
    IClientValidatable
{
    public override bool IsValid(object value)
    {
        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "mycustomvalidator",
        };

        var viewContext = (ViewContext)context;
        var dependentProperty1 = viewContext.ViewData.TemplateInfo
            .GetFullHtmlFieldId("DependentProperty1");
        //var prefix = viewContext.ViewData.TemplateInfo.HtmlFieldPrefix;

        rule.ValidationParameters.Add("dependentproperty1", dependentProperty1);

        yield return rule;
    }
}

在客户端执行时,服务器属性被忽略,反之亦然。

如果您需要在类上具有验证属性,则验证可能会针对多个字段进行。我添加了一些样板代码,用于将附加参数传递给客户端验证方法,但它没有按我的预期工作。在我的实际代码中,我注释掉了 viewContext 和 dependentProperty1 变量,并将“DependentProperty1”字符串传递给了rule.ValidationParameters.Add 方法的第二个参数。由于某种原因,我得到了不正确的 HtmlFieldPrefix。如果有人可以帮助解决这个问题,请发表评论...

无论如何,您最终会得到这样的视图模型:

[MyCustomServerValidation(ErrorMessage = MyCustomValidationMessage)]
public class MyCustomViewModel
{
    private const string MyCustomValidationMessage = "user error!";

    [Display(Name = "Email Address")]
    [MyCustomClientValidation(ErrorMessage = MyCustomValidationMessage)]
    public string Value { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string DependentProperty1 { get; set; }
}

这样的客户端脚本:

/// <reference path="jquery-1.6.2.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

$.validator.addMethod('mycustomvalidator', function (value, element, parameters) {
    var dependentProperty1 = $('#' + parameters['dependentproperty1']).val();
    // return true or false
});
$.validator.unobtrusive.adapters.add('mycustomvalidator', ['dependentproperty1'], 
    function (options) {
        options.rules['mycustomvalidator'] = {
            dependentproperty1: options.params['dependentproperty1']
        };
        options.messages['mycustomvalidator'] = options.message;
    }
);

和这样的视图:

@Html.EditorFor(m => m.Value)
@Html.EditorFor(m => m.DependentProperty1)
@Html.ValidationMessageFor(m => m.Value)
@Html.ValidationMessageFor(m => m)

然后,如果您禁用了客户端验证,则 @Html.ValidationMessageFor显示 (m => m) 而不是属性的显示。

I found this answer while looking for a solution to the same problem, and came up with a workaround.

Instead of 1 ValidationAttribute, have 2:

1.) A ServerValidationAttribute will be on the class, and will not implement IClientValidatable.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MyCustomServerValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // remember to cast to the class type, not property type
        // ... return true or false
    }
}

2.) A ClientValidationAttribute will be on the field / property, and will implement IClientValidatable, but the IsValid override always returns true.

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, 
    AllowMultiple = false, Inherited = true)]
public class MyCustomClientValidationAttribute : ValidationAttribute, 
    IClientValidatable
{
    public override bool IsValid(object value)
    {
        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "mycustomvalidator",
        };

        var viewContext = (ViewContext)context;
        var dependentProperty1 = viewContext.ViewData.TemplateInfo
            .GetFullHtmlFieldId("DependentProperty1");
        //var prefix = viewContext.ViewData.TemplateInfo.HtmlFieldPrefix;

        rule.ValidationParameters.Add("dependentproperty1", dependentProperty1);

        yield return rule;
    }
}

When executed on the client, the server attribute is ignored, and vice versa.

If you need to have a validation attribute on the class, chances are the validation happens against multiple fields. I dropped in some boilerplate code for passing additional parameters to the client validation method, but it's not working as I expected. In my actual code I have commented out the viewContext and dependentProperty1 vars, and just passed a "DependentProperty1" string to the second argument of the rule.ValidationParameters.Add method. For some reason, I'm getting an incorrect HtmlFieldPrefix. If anyone can help with this please comment...

Anyway, you end up with a viewmodel like this:

[MyCustomServerValidation(ErrorMessage = MyCustomValidationMessage)]
public class MyCustomViewModel
{
    private const string MyCustomValidationMessage = "user error!";

    [Display(Name = "Email Address")]
    [MyCustomClientValidation(ErrorMessage = MyCustomValidationMessage)]
    public string Value { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string DependentProperty1 { get; set; }
}

A client script like this:

/// <reference path="jquery-1.6.2.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

$.validator.addMethod('mycustomvalidator', function (value, element, parameters) {
    var dependentProperty1 = $('#' + parameters['dependentproperty1']).val();
    // return true or false
});
$.validator.unobtrusive.adapters.add('mycustomvalidator', ['dependentproperty1'], 
    function (options) {
        options.rules['mycustomvalidator'] = {
            dependentproperty1: options.params['dependentproperty1']
        };
        options.messages['mycustomvalidator'] = options.message;
    }
);

And a view like this:

@Html.EditorFor(m => m.Value)
@Html.EditorFor(m => m.DependentProperty1)
@Html.ValidationMessageFor(m => m.Value)
@Html.ValidationMessageFor(m => m)

Then if you have client validation disabled, the @Html.ValidationMessageFor(m => m) is displayed instead of the one for the property.

心的憧憬 2024-11-10 18:08:40

不,这是不可能的。对不起。

Nope, it's not possible. Sorry.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文