为什么在document.ready运行之前必须添加自定义的Unobtrusive Validator方法? [英] Why do custom Unobtrusive Validator methods have to be added before document.ready runs?

查看:210
本文介绍了为什么在document.ready运行之前必须添加自定义的Unobtrusive Validator方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发MVC4应用程序,并且需要对特定表单进行一些特定的验证.因此,我遵循了(几个)关于如何执行此操作的教程.从自定义属性开始:

I'm working on an MVC4 app and needed some specific validation on a particular form. So I followed (several) tutorials on how to do this. Starting with a custom attribute:

public class CheckDuplicateElementNameAttribute : 
    ValidationAttribute, IClientValidatable
{
  // Server side check omitted
  public IEnumerable<ModelClientValidationRule>
        GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  {
        ModelClientValidationRule rule = new ModelClientValidationRule();
        rule.ErrorMessage = this.ErrorMessage;
        rule.ValidationType = "elementname";
        yield return rule;
  }
}

因此,我将属性添加到模型的属性中,如下所示:

So then I add the attribute to the model's property like so:

public class HygieneElementModel
{

    [CheckDuplicateElementName
        (ErrorMessage="There is already an element with that name")]
    public string ShortName { get; set; }

}

最后将js方法添加到页面:

And finally added the js method to the page:

$(document).ready(function () {
        jQuery.validator.addMethod('elementname', function (val, element) {
        console.log('validating');
        return false;
    }, '');

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

    jQuery.validator.unobtrusive.parse();
}

并且验证方法完全无法运行.当我将这些行移出document.ready函数,并让它们在加载后立即运行时,就可以正常工作.现在,我遵循的许多示例-其中许多来自SO,都显示了在document.ready中进行的addMethod调用,那么为什么我的这种方法无法正常工作?

And the validation method completely fails to run. When I move the lines out of the document.ready function and just have them run as soon as they are loaded, it works fine. Now, a lot of the examples I've followed - many of them from SO, show the addMethod calls being made from within document.ready, so why does mine not work this way?

问题:

  1. 这是为什么?
  2. 什么时候注册了默认适配器,并且它们如何在html加载之前对其进行解析?
  3. 是否存在在缓慢连接时仍然无法按时注册验证适配器的风险?

版本详情

jQuery 1.11.0

jQuery 1.11.0

jQuery.validation 1.8.1

jQuery.validation 1.8.1

Mircosoft.jQuery.Unobstrusive.Ajax 3.2.0

Mircosoft.jQuery.Unobstrusive.Ajax 3.2.0

Mircosoft.jQuery.Unobstrusive.Validation 3.2.0

Mircosoft.jQuery.Unobstrusive.Validation 3.2.0

推荐答案

This article from Brad Wilson covers all your questions.

1这是为什么?

1 Why is this?

请参见本文的解析新HTML以进行验证.它说

页面加载完成后,不打扰的客户端验证脚本会自动为验证规则解析HTML的初始集合.如果您的页面动态地添加新的HTML内容(也许通过Ajax或通过客户端应用程序代码),则您可能希望解析该新HTML以便在新HTML元素上进行客户端验证.

The unobtrusive client validation script automatically parses the initial set of HTML for validation rules when the page has finished loading. If your page dynamically adds new HTML content (perhaps throught Ajax or through client-side application code), you may wish to parse that new HTML for client validation on the new HTML elements.

要解析新的HTML,您可以调用jQuery.validator.unobtrusive.parse()方法,并向其传递您要解析的HTML的选择器.

To parse new HTML, you can call the jQuery.validator.unobtrusive.parse() method, passing it a selector for the HTML that you would like to be parsed.

我认为jquery.validate.unobtrusive.js包含在文档准备好功能的页面之前中,并且由于它使用了自己的文档准备好功能来解析html页面-它不使用您的适配器,因为您的当时尚未执行文档就绪处理程序(没有可用的自定义适配器).当您将适配器添加到文档准备就绪功能之外时,它们在jquery.validate.unobtrusive.js的文档准备就绪状态下可用.

I believe that jquery.validate.unobtrusive.js is included in the page before your document ready function and as it uses it's own document ready function which parses html page - it doesn't use your adapter, because your document ready handler has not been executed at that moment (no custom adapters available). When you move adding your adapter outside document ready function, they're available at the jquery.validate.unobtrusive.js's document ready.

2默认适配器何时注册?如何在加载html之前解析它们?

2 When are the default adapters registered and how do they parse the html before it is loades?

请参见文章的桥接HTML和jQuery验证:适配器部分:

在jQuery.validator.unobtrusive.adapters上有一个可用的适配器集合.

There is an adapter collection available at jQuery.validator.unobtrusive.adapters.

您可以看到 jquery.validate.unobtrusive.js源代码以确保所有初始化(以及默认适配器)都在脚本中正确进行,该脚本再次在页面文档准备好之前执行.

You can see jquery.validate.unobtrusive.js source code to ensure that all initialization (default adapters as well) is happen right in the script, which, again, executes before your page's document ready.

文档解析发生在脚本的结尾-在文档准备功能中:

The document parsing is happen in the end of the script - in it's document ready function:

$(function () {
    $jQval.unobtrusive.parse(document);
});

3是否存在在缓慢连接时仍然无法按时注册验证适配器的风险?

3 Is there a risk that on a slow connection the validation adapter still won't be registered on time?

好吧-根本没有魔术,如果您正确理解了脚本的行为,并且以正确的方式进行了初始化,那一切都会好起来的:)

Well - there's no magic at all, if you understand the script behaviour correctly and if you do initialization in the right way, it'll all be ok :)

要确保您的适配器正在使用,您可以:

To ensure your adapters are using, you can:

1)将它们注册到文档外部,就像一切正常一样.

1) register them outside document ready as you did when it all worked.

2)将其注册到文档准备功能中,但将<script>标记移至文档准备功能下方,其中包括jquery.validate.unobtrusive.js.

2) register them in document ready function, but move <script> tag which includes jquery.validate.unobtrusive.js below your document ready function.

3)致电

jQuery.validator.unobtrusive.parse(document);

在注册自定义适配器后手动进行操作(如果您不太担心性能问题的话).

manually after registering your custom adapters (if you're not so much concern about performance).

这篇关于为什么在document.ready运行之前必须添加自定义的Unobtrusive Validator方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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