带参数的 ASP.NET MVC 3 客户端验证 [英] ASP.NET MVC 3 client-side validation with parameters

查看:25
本文介绍了带参数的 ASP.NET MVC 3 客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继此帖子 执行自定义客户端验证属性

我想弄清楚如何做到这一点,将额外的参数传递给客户端脚本

I am trying to get my head around how to do this, passing additional parameters to the client-side script

据我所知,使用 MVC 3 实现自定义验证需要以下内容

As I understand it so far to implement custom validation with MVC 3 the following is required

基于 ValidationAttribute 并实现 IClientValidatable.我还看到了一些源自 ModelValidator 的示例,它们似乎实现了 ValidationAttribute 和 IClientValidatable 的功能.所以这是我关于差异是什么或 ModelValidator 是否在 MVC 2 中使用但现在已弃用或什么的第一个困惑点?

Based on ValidationAttribute and implementing IClientValidatable. I have also see some examples deriving from ModelValidator, which seems to implement the functionality of both ValidationAttribute and IClientValidatable. So this is my first point of confusion as to what the diffirences are or whether ModelValidator was used in MVC 2 but is now deprecated or what ?

必须从 GetClientValidationRules() 返回 ModelClientValidationRule 的实例以指定详细信息,例如错误消息、ValidationType(我理解为将执行客户端验证的 Javascript 函数的名称)和任何其他自定义参数该属性可能具有,并且需要传递给 Javascript 验证.

An instance of ModelClientValidationRule must be returned from GetClientValidationRules() to specify details such as the error message, ValidationType (which I understand to be the name of the Javascript function that will perform the client-side validation) and any additional custom parameters that the attribute may have, and that need to be passed to the Javascript validation.

我假设运行时(不确定它的哪一部分)然后使用 ModelClientValidationRule 在标签元素中生成 html 属性,如下所示:

I assume that the runtime (not sure which part of it) then use the ModelClientValidationRule to generate html attribute in the tag elements as follows:

data-val="true"  (to indicate that the element requires validation)
data-val-[ValidationType]=[ErrorMessage]
data-val-[ValidationType].[ValidationParameters(n).Key]=[ValidationParameters(n).Value]

实现客户端验证逻辑

必须使用 jQuery.validators.addmethod() 创建一个 Javascript 函数并将其添加到 jQuery.validators 中,以便 JQuery 在需要执行时知道它.类似的东西:

Implement the client-side validation logic

A Javascript function must be created and added to jQuery.validators with jQuery.validators.addmethod() so that JQuery is aware of it when it need to be executed. Something like:

jQuery.validator.addMethod(
    'greaterThan', 
    function (value, element, params) {
        /.../
       return /* true or false   */ ; 
    },
    ''
); 

我的问题是签名函数(值,元素,参数)"是否是处理验证的方法的标准,我假设它会在适当的时间被一些 jQuery 功能调用,例如在提交表单之前或者当一个元素丢失 fuces 或 keyUp 事件时.我只是不明白您如何控制这一点,即选择哪个事件适合您的自定义验证.

My question here is whether the signature 'function (value, element, params)' is standard for methods that will handle validation and I assume it will be called by some jQuery functionality at the appropriate time such as before a form is submitted or when an element looses fuces or on keyUp events. I just don't undertand how you can controll this i.e. choose which event is appropriete for yout custom validation.

这将不显眼的属性转化为;我不是很清楚,但假设它是一个 jQuery 规则,但我不清楚它们是如何工作的.类似的东西

This translates unobtrusive attributes to; something I am not very clear on, but assume it to be a jQuery Rule, but I am not clear on how those work. Something like

jQuery.validator.unobtrusive.adapters.add(
    'futuredate', 
    { },
    function (options) {
        options.rules['greaterThan'] = true;
        options.messages['greaterThan'] = options.message;
    }
); 

我的问题是关于功能(选项)".这是将在'function (value, element, params)'之前调用的函数,负责将不显眼的标签提取到jQuery.Validation可以理解的数据结构中.从代码示例中,在我看来,options 是一个对象,它包含来自标记的属性值(例如 options.message)和它必须映射到的 jQuery 相关属性(例如 options.messages['ClientSideValidationFunctionName']. 如果是,如何检索和映射自定义参数.

My question here is about 'function (options)'. Is this the function that will be called before 'function (value, element, params)' and is responsible for extracting the unobtrusive tags into a data structure that can be understood by jQuery.Validation. From the code example it seems to me that options is an object that contains both, the attribute values from the tag (such as options.message) and the jQuery relevant properties it must map to (such as options.messages['ClientSideValidationFunctionName']. If so how are custom parameters retrieved and mapped.

我希望我没有增加任何额外的混乱.

I hope I have not added any additional confusion.

推荐答案

您可以使用 ValidationParameters 属性以将自定义参数添加到规则:

You could use the ValidationParameters property to add custom parameters to the rule:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = this.ErrorMessage,
        ValidationType = "futuredate",
    };
    rule.ValidationParameters.Add("param1", "value1");
    rule.ValidationParameters.Add("param2", "value2");
    yield return rule;
}

可以在适配器中使用:

jQuery.validator.unobtrusive.adapters.add(
    'futuredate', 
    [ 'param1', 'param2' ],
    function (options) {
        var param1 = options.params.param1; // shall equal 'value1'
        var param2 = options.params.param2; // shall equal 'value2'
        // TODO: use those custom parameters to define the client rules
    }
);

<小时>

更新:

根据评论部分的要求,您可以将这些参数传递给自定义验证器规则函数:

As requested in the comments section here's how you could pass those parameters to the custom validator rule function:

jQuery.validator.unobtrusive.adapters.add(
    'futuredate', 
    [ 'param1', 'param2' ],
    function (options) {
        // simply pass the options.params here
        options.rules['greaterThan'] = options.params;
        options.messages['greaterThan'] = options.message;
    }
);

jQuery.validator.addMethod('greaterThan', function (value, element, params) {
    // params here will equal { param1: 'value1', param2: 'value2' }
    return ...
}, '');

这篇关于带参数的 ASP.NET MVC 3 客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆