asp.net-mvc 带参数的 ASP.NET MVC 3 客户端验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4784943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:47:20  来源:igfitidea点击:

ASP.NET MVC 3 client-side validation with parameters

asp.net-mvcvalidationasp.net-mvc-3parametersclient-side

提问by ricardo

Following on from this post Perform client side validation for custom attribute

继这篇文章后为自定义属性执行客户端验证

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

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

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

据我了解,到目前为止,使用 MVC 3 实现自定义验证需要以下内容

Create a custom validation attribute

创建自定义验证属性

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 ?

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

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.

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

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

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

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

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.validators.addmethod() 创建一个 Javascript 函数并将其添加到 jQuery.validators 中,以便 JQuery 在需要执行时知道它。就像是:

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

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 功能调用,例如在提交表单之前或当元素丢失 fuces 或 keyUp 事件。我只是不明白您如何控制这一点,即选择哪个事件适合您的自定义验证。

Implement an unobtrusive adapter

实现一个不显眼的适配器

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 规则,但我不清楚这些是如何工作的。就像是

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

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.

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

I hope I have not added any additional confusion.

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

回答by Darin Dimitrov

You could use the ValidationParametersproperty to add custom parameters to the rule:

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

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

which could be used in the adapter:

可以在适配器中使用:

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


UPDATE:

更新:

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 ...
}, '');