jQuery 验证无法正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15995017/
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-08-26 16:09:50  来源:igfitidea点击:

jQuery validate not working properly

jqueryjquery-validate

提问by Lurk21

I need this validation to fire when the div button is clicked. If the validation is successful, I want it to alert "is good".

我需要在单击 div 按钮时触发此验证。如果验证成功,我希望它提醒“很好”。

Unfortunately, although validation fires and all rules are checked, it does not error if a required field is blank. It will error for any of the other checks tho.

不幸的是,虽然验证会触发并且所有规则都被检查,但如果必填字段为空,它不会出错。其他任何检查都会出错。

Finally, if I fill in the fields correctly and click the button, nothing happens.

最后,如果我正确填写字段并单击按钮,则没有任何反应。

JS:

JS:

$(document).ready(function() {

// Submit prompted password reset
$("#passwordResetButton").click(function() {

    $("#passwordResetForm").validate({  
        rules: {
            password: { required: true, minlength: 8, maxlength: 40, remote: { url: "/ajax/isPasswordOK", data: { product: function() { return $("#password").val();  } } } },
            confirmPassword: { required: true, equalTo: "#password" },
        }, 
        messages: { 
            password: { required: "Please enter a password", minlength: "Password must be at least 8 characters long", remote: "Password should contain: <li>At least one upper case character <li>At least one lower case character <li>At least one number <li>And may not contain any of the following: \;-\")(&*='|$" },
            confirmPassword: { required: "Please confirm your password", equalTo: "The passwords do not match" },
          }, 
        onkeyup: false, //turn off auto validate whilst typing
        onblur: true,
        afterValidation: function() {
            alert('is good');
        }
    });
});
});

HTML:

HTML:

<form id="passwordResetForm" style="width: 480px; margin: auto;">
        <div class="row"><p class="lead">Let's reset that password</p></div>
        <div class="row">
            <div class="small-8 large-4 columns"><label>New Password:</label></div>
            <div class="small-12 large-6 columns"><input name="password" id="password" type="password" size="20"/></div>
        </div>
        <div class="row">
            <div class="small-8 large-4 columns"><label>Confirm Password:</label></div>
            <div class="small-12 large-6 columns"><input name="confirmPassword" id="confirmPassword" type="password" size="20"/></div>
        </div>
        <div class="row">
            <div class="large-offset-10 small-3 large-1 columns">
                <div id="passwordResetButton"  class="small button">Submit</div>
            </div>
        </div>
    </form>

回答by Sparky

There are a few problems with your code.

您的代码存在一些问题。

1) .validate()is the initializationmethod of the plugin, not a method for testing the form. In other words, do not put it inside of a clickhandler or it won't be ready when you need it. Put .validate()inside of the DOM ready event handler so it's fired once when the page is created, then the form is immediately ready for validation.

1) .validate()是插件的初始化方法,不是测试表单的方法。换句话说,不要将它放在click处理程序中,否则在您需要时它不会准备好。放在.validate()DOM 就绪事件处理程序内部,以便在创建页面时触发一次,然后表单立即准备好进行验证。

2) There is no such option as onblurfor this plugin. It is called onfocusoutand the option is already activated by default. Setting this type of option to trueis not validand will likely break something, so simply leave it out of the initialization entirely.

2)onblur对于这个插件没有这样的选项。它被调用onfocusout并且该选项默认已被激活。 将此类型的选项设置true为无效并且可能会破坏某些内容,因此只需将其完全排除在初始化之外。

3) There is no such option/function called afterValidation:. You cannot just "invent" callback functions... jQuery plugins have to have these things already specifically built into them. If you want to fire something on a valid form, use the supplied submitHandler:callback function.

3) 没有这样的选项/函数称为afterValidation:. 你不能只是“发明”回调函数……jQuery 插件必须将这些东西专门内置到它们中。如果要在有效表单上触发某些内容,请使用提供的submitHandler:回调函数。

submitHandler: function (form) {
    alert('is good');
    return false;
}

4) Use a <input type="submit" />or a <button type="submit">Submit</button>for the form's submit. This way, the plugin can automatically capture the click event and handle the submit as designed.

4) 使用 a<input type="submit" />或 a<button type="submit">Submit</button>来提交表单。这样,插件可以自动捕获点击事件并按设计处理提交。

5) Minor note: For your custom messages, simply use {0}and the rule's parameter will be inserted automatically. This kind of code is easier to maintain.

5) 小注:对于您的自定义消息,只需使用即可{0}自动插入规则的参数。这种代码更容易维护。

minlength: "Password must be at least {0} characters long",

Working Demo: http://jsfiddle.net/J9N3g/

工作演示:http: //jsfiddle.net/J9N3g/

I suggest that you review the full documentation here: http://docs.jquery.com/Plugins/Validation

我建议您在此处查看完整文档:http: //docs.jquery.com/Plugins/Validation

jQuery:

jQuery

$(document).ready(function () {

    $("#passwordResetForm").validate({
        rules: {
            password: {
                required: true,
                minlength: 8,
                maxlength: 40,
                remote: {
                    url: "/ajax/isPasswordOK",
                    data: {
                        product: function () {
                            return $("#password").val();
                        }
                    }
                }
            },
            confirmPassword: {
                required: true,
                equalTo: "#password"
            },
        },
        messages: {
            password: {
                required: "Please enter a password",
                minlength: "Password must be at least {0} characters long",
                remote: "Password should contain: <li>At least one upper case character <li>At least one lower case character <li>At least one number <li>And may not contain any of the following: \;-\")(&*='|$"
            },
            confirmPassword: {
                required: "Please confirm your password",
                equalTo: "The passwords do not match"
            },
        },
        onkeyup: false, //turn off auto validate whilst typing
        submitHandler: function (form) {
            alert('is good');
            return false;
        }
    });

});

HTML:

HTML:

<form id="passwordResetForm" style="width: 480px; margin: auto;">
    <div class="row">
        <p class="lead">Let's reset that password</p>
    </div>
    <div class="row">
        <div class="small-8 large-4 columns">
            <label>New Password:</label>
        </div>
        <div class="small-12 large-6 columns">
            <input name="password" id="password" type="password" size="20" />
        </div>
    </div>
    <div class="row">
        <div class="small-8 large-4 columns">
            <label>Confirm Password:</label>
        </div>
        <div class="small-12 large-6 columns">
            <input name="confirmPassword" id="confirmPassword" type="password" size="20" />
        </div>
    </div>
    <div class="row">
        <div class="large-offset-10 small-3 large-1 columns">
            <input type="submit" id="passwordResetButton" class="small button" />
        </div>
    </div>
</form>

回答by Tamil Selvan C

Change to

改成

afterValidation: function() {
            alert('is good');
        }

to

submitHandler: function() { alert("is good!") }:

See jquery validate option: http://docs.jquery.com/Plugins/Validation/validate

请参阅 jquery 验证选项:http: //docs.jquery.com/Plugins/Validation/validate

Change div to button, it a best practice

将 div 更改为按钮,这是最佳实践

<div id="passwordResetButton"  class="small button">Submit</div>

to

<button id="passwordResetButton"  class="small button">Submit</button>