【问题标题】:jQuery custom rule always returning truejQuery 自定义规则总是返回 true
【发布时间】:2014-01-30 22:22:30
【问题描述】:

我正在使用带有 jQ​​uery 步骤和 jQuery 验证的 jQuery。

我为一段代码编写了一些自定义规则,但是这些规则无法正常工作。

这是我的html代码:

<h2>Second Step</h2>
<section>
    <form id="SecondStep" >
        <section class="expose">
            <div class="label-field clearfix">
                <fieldset data-role="controlgroup">
                    <legend>Textbox</legend>
                    <input type="text" id="textbox" name="textbox" />
                </fieldset>
            </div>
            <div class="label-field clearfix">
                <fieldset data-role="controlgroup">
                    <legend>Password</legend>
                    <input type="password" id="password" name="password" />
                </fieldset>
            </div>
        </section>
    </form>
</section>

这是我的自定义规则:

$("#SecondStep").validate({
    rules: {
        textbox: "required",
        password: {
            required: true,
            minlength: 5
        }
    },
    messages: {
        textbox: "Please enter information into the textbox",
        password: {
            required: "Please enter a password",
            minlength: "Your password must consist of at least 5 characters"
        }                           
    }
});

这是我从按钮的 onClick 调用以测试我的自定义规则的代码:

function validateAllElements()
{
     var isValid = $("#SecondStep").valid(); 
     alert(isValid);
}

当我调用 validateAllElements 函数时,即使我在文本框和密码表单元素中根本没有值,.valid 方法也会返回 true。

我可以对这段代码有帮助吗?

提前致谢

【问题讨论】:

    标签: javascript jquery jquery-validate jquery-steps


    【解决方案1】:

    在使用JSFiddle 进行几次测试后,如果将代码包装到$(document).ready(function() {}) 中,您的代码似乎可以工作。

    $(document).ready(function() {
        $("#SecondStep").validate({
        rules: {
            textbox: "required",
            password: {
                required: true,
                minlength: 5
            }
        },
        messages: {
            textbox: "Please enter information into the textbox",
            password: {
                required: "Please enter a password",
                minlength: "Your password must consist of at least 5 characters"
            }                           
        }
        });
        $('#test').click(function () {
             var isValid = $("#SecondStep").valid(); 
             alert(isValid);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      相关资源
      最近更新 更多