【问题标题】:jQuery Validate not triggeringjQuery Validate 未触发
【发布时间】:2015-06-02 23:35:49
【问题描述】:

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

<!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>

【问题讨论】:

    标签: jquery jquery-validate


    【解决方案1】:
    <script type="text/javascript" src="jquery.validate.unobtrusive.min.js"></script>
    

    为什么要包含unobtrusive 插件?

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

    为什么?

    因为unobtrusive插件会根据HTML属性自动构造和调用.validate()方法。

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

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

    由于unobtrusive 插件,您对.validate() 的调用会被jQuery Validate 完全忽略。这就是为什么它只有在您将 required 属性放在您的 input 元素中时才有效。

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

    http://jsfiddle.net/ocx864nu/

    【讨论】:

      猜你喜欢
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 2011-02-13
      相关资源
      最近更新 更多