jQuery 在同一页面上验证多个表单

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

Validating multiple forms on the same page

jqueryjquery-validate

提问by Wizard

For example I have 3 forms in a page with the same names. How can I validate all these forms with one validate method?

例如,我在一个页面中有 3 个具有相同名称的表单。如何使用一种验证方法验证所有这些表单?

<form id="formID">
<input name="nick">
<input type="submit">
</form>

<form id="formID">
<input name="nick">
<input type="submit">
</form>

<form id="formID">
<input name="nick">
<input type="submit">
</form>

I want to validate only the submitted form not all at the same time.

我只想验证提交的表单,而不是同时验证所有表单。

$('#formID').validate({
})

My solution does not work. I also find I can't add different IDs because these forms are in a PHP loop and it must have same ID.

我的解决方案不起作用。我还发现我无法添加不同的 ID,因为这些表单位于 PHP 循环中,并且必须具有相同的 ID。

采纳答案by Irshad Khan

Here is the Solution to Validate Multiple Forms on a Single Page :

这是在单个页面上验证多个表单的解决方案:

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

<script type="text/javascript">
  $(document).ready(function () {
    $("form").submit(function () {

      var clikedForm = $(this); // Select Form

      if (clikedForm.find("[name='mobile_no']").val() == '') {
        alert('Enter Valid mobile number');
        return false;
      }
      if (clikedForm.find("[name='email_id']").val() == '') {
        alert('Enter  valid email id');
        return false;
      }

    });
  });
</script>

It is working for me. I wrote this code for 5 Forms in a single Page.

它对我有用。我在一个页面中为 5 个表单编写了这段代码。

回答by Sparky

When you need to apply the same .validate()method to multiple forms, you simply need a jQuery .each()and you can target them all at once by the formtag.

当您需要将相同的.validate()方法应用于多个表单时,您只需要一个jQuery.each(),您就可以通过form标签一次将它们全部定位。

$('form').each(function() {   // <- selects every <form> on page
    $(this).validate({        // <- initialize validate() on each form
        // your options       // <- set your options inside
    });
});

DEMO: http://jsfiddle.net/K6Tkn/

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



Quote OP:

引用 OP:

"I also find I can't add different IDs because these forms are in a PHP loop and it must have same ID."

“我还发现我无法添加不同的 ID,因为这些表单位于 PHP 循环中,并且必须具有相同的 ID。”

Then your PHP loop is not constructed properly. Every idon a page must be unique or the HTML markup is invalid. You can simply use classinstead of id. Otherwise, if there are no other <form>elements on the page, you can target them all with $('form')as done in the demo above.

那么你的 PHP 循环构造不正确。 页面上的id一个都必须是唯一的,否则 HTML 标记是无效的。您可以简单地使用class代替id。否则,如果<form>页面上没有其他元素,您可以$('form')按照上面的演示中的方法将它们全部定位。

回答by Janne Savolainen

I've created fiddlefor you. Add ids if you really need them.

我已经为你创造了小提琴。如果您确实需要它们,请添加 ID。

Key is to add same class to forms and validate each form.

关键是向表单添加相同的类并验证每个表单。

$('form.validateForm').each(function(key, form) {
    $(form).validate(); 
});

回答by Sandy

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title></title>
<link href="<c:url value="/resources/js/bootstrap/3.3.7/css/bootstrap.min.css"/>" rel="stylesheet" />
<script src="<c:url value="/resources/js/bootstrap/jquery/1.9.1/jquery-1.9.1.min.js"/>"></script>
<script src="<c:url value="/resources/js/jquery_validation/jquery.validate.min.js"/>"></script>
<script src="<c:url value="/resources/js/bootstrap/3.3.7/js/bootstrap.min.js"/>"></script>
<style>
.error {
    color: red;
    font-size: 0.8em;
}

body {
    margin: 30px;
}
</style>
</head>
<body>

    <form id="formA">
        <input type="text" name="username" />
        <input type="submit" value="submit" />
    </form>

    <form id="formB">
        <input type="text" name="email" />
        <input type="submit" value="submit" />
    </form>

</body>

<script>
    $(document).ready(function() {
        $('#formA').validate({
            rules:{
                username:{
                    required:true,

                }
            }, 
            submitHandler:function(event){
                alert('prevent default');
                alert('submit handler for formA')
            }
        });
        $('#formB').validate({
            rules:{
                email:{
                    required:true,
                    email:true
                }
            }, 
            submitHandler:function(event){
                alert('prevent default');
                alert('submit handler for formB')
            }
        });
    });
</script>


</html>

回答by Hassan Tahir

Inspired by the answer of @Irshad Khan, hope it may help others. Apply data-rule-required="true"to required HTML inputs then in jQuery

受到@Irshad Khan 的回答的启发,希望它可以帮助其他人。应用于data-rule-required="true"所需的 HTML 输入,然后在 jQuery 中

$('form').submit(function (e) {
        e.preventDefault();
        var clikedForm = $(this);
        if (clikedForm.valid()) {
            alert('valid');
        } else {
            alert('not_valid');
        }
    });

回答by Devsainii

Just insert below code on your page & use as many forms you want.

只需在您的页面上插入以下代码并使用您想要的任意数量的表单。

<script type="text/javascript">
        $(document).ready(function () {

            $('form').each(function () {
                $(this).validate({
                    // your options
                });
            });

        });
    </script>