jQuery 验证插件在按钮单击时验证表单

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

jQuery Validation plugin validating form on button click

jqueryformsjquery-validate

提问by Art Taylor

So I have a seven part form where six tabs are hidden via CSS and when a user clicks next another part fades in.

所以我有一个七部分的表单,其中六个选项卡通过 CSS 隐藏,当用户单击下一个时,另一个部分会淡入。

I've submitted the page to make sure the plugin is working; it is. Essentially its just going to the next part of the form without validation the current part

我已提交页面以确保插件正常工作;这是。本质上它只是转到表单的下一部分而不验证当前部分

As an example

举个例子

HTML

HTML

<form id = "form1" action = "backend.php" method = "post">
<label for "phone">First Name </label>
    <input type = "text" name = "fName" placeholder = "First Name..." class = "required" id = "fName" />
<button id = "btn" type = "button" class = "buttonnav next">next</button>
</form>

Javascript

Javascript

$('#btn').click( function() { $("#form1").validate();});

回答by Sparky

If you're using the jQuery Validateplugin, with your code, the plugin is not initialized until after the button is clicked. If the plugin is not initialized, then there's no validation.

如果您使用的是 jQuery Validate插件,那么在您的代码中,该插件直到按钮被点击后才会被初始化。如果插件未初始化,则没有验证。

$('#btn').click( function() { $("#form1").validate();});

Instead, .validate()gets called once on DOM ready to initializethe plugin on the form.

相反,.validate()在 DOM 上调用一次,准备初始化表单上的插件。

If you want to testthe form at any time after initialization, you would use the .valid()method.

如果您想在初始化后随时测试表单,您可以使用.valid()方法

$(document).ready(function () {

    $('#form1').validate({ // initialize plugin
        // your options
    });

    $('#btn').click( function() { 
        $("#form1").valid();  // test the form for validity
    });

});


I have no idea how you've set up each part to to interact with each other or what other code is being used. Based on your OP alone, here is a working example using my answer above.

我不知道您如何设置每个部分以相互交互或使用什么其他代码。仅基于您的 OP,这是一个使用我上面的回答的工作示例。

DEMO: http://jsfiddle.net/pqVJM/

演示:http: //jsfiddle.net/pqVJM/

$(document).ready(function () {

    $('#form1').validate();

    $('#btn').click(function () {
        if ($("#form1").valid()) {
            alert('hello - valid form');
        }
    });

});