jQuery验证未触发 [英] jQuery Validate not triggering

查看:84
本文介绍了jQuery验证未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html和js,但它不会触发对文本输入字段模糊或表单提交的jquery.validate验证.如果我直接在文本输入字段中添加必需"属性,则会显示默认错误消息.谁能帮我弄清楚为什么下面的方法不起作用?

I have the following html and js, but it is not triggering the jquery.validate validation on text input field blur or form submit. If I add "required" attribute directly to the text input field, the default error message kicks in instead. Can anyone please help me figure out why the below does not work?

<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery.validate.unobtrusive.min.js"></script>

</head>
<body>
    <form id="test" action="test.html" method="post">
        <input type="text" name="txtName" />    
        <input type="submit" name="btnSubmit" />
    </form>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function(){
        ValidateForm();

    });

    function ValidateForm(){
        $.validator.unobtrusive.parse($("form"));

        $('#test').validate({
            rules: {
                "txtName": "required"
            },
            messages: {
                "txtName": "this name is required for sure!"
            },
            errorPlacement: function (error, element) {
                $(element).parent().append(error);
            },
            onfocusout: function (element) { this.element(element); }
        });
    }
</script>

推荐答案

<script type="text/javascript" src="jquery.validate.unobtrusive.min.js"></script>

为什么要包含unobtrusive插件?

您自己不能在调用.validate()方法时同时使用unobstrusive插件.

You cannot simultaneously use the unobstrusive plugin while calling the .validate() method yourself.

为什么?

因为unobtrusive插件会基于HTML属性自动构造并调用.validate()方法.

Because the unobtrusive plugin automatically constructs and calls the .validate() method based on the HTML attributes.

由于该插件仅使用对.validate()的第一次调用来初始化验证,因此它将自动忽略所有后续调用.因此,您对.validate()的调用将被完全忽略.

Since the plugin only uses the first call to .validate() to initialize validation, it automatically ignores all subsequent calls. So your call to .validate() is totally ignored.

如果我直接在文本输入字段中添加必填",则会显示默认错误消息.

If i add "required" directly to the text input field, the default error message kicks in instead.

由于使用了unobtrusive插件,因此jQuery Validate完全忽略了对.validate()的调用.这就是为什么仅在将required属性放在input元素内时有效的原因.

Because of the unobtrusive plugin, your call to .validate() is totally ignored by jQuery Validate. That is why it only works when you put the required attribute within your input element.

完全删除unobtrusive插件,即可正常工作:

Completely remove the unobtrusive plugin and it works fine:

http://jsfiddle.net/ocx864nu/

http://jsfiddle.net/ocx864nu/

这篇关于jQuery验证未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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