6

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

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

Sparky
  • 98,165
  • 25
  • 199
  • 285
Wizard
  • 10,985
  • 38
  • 91
  • 165
  • PHP has nothing to do with ids that you give to forms. Also id should be unique. Are you using [jquery validation plugin](http://jqueryvalidation.org/)? – Janne Savolainen May 29 '14 at 19:26
  • 2
    "it must have same ID" < and for that reason, I'm out. Rethink this one, Tomas. – Moby's Stunt Double May 29 '14 at 19:31
  • This is company person "profiles" it forms must have same ID. – Wizard May 29 '14 at 19:32
  • That doesn't make sense as you will be producing poorly collated markup, why not apply a common css class to the forms for mass targeting, and the PersonID into the id attribute? – Moby's Stunt Double May 29 '14 at 19:37
  • 1
    **Every `id` on a page must be unique or the HTML markup is invalid**. You're also going to have more problems than just with jQuery Validate. – Sparky May 29 '14 at 19:51
  • 1
    You asked specifically about the jQuery Validate plugin and then eventually accepted an answer that has absolutely nothing to do with this plugin. – Sparky Oct 28 '18 at 16:44
  • Possible duplicate of [jQuery multiple form validation](https://stackoverflow.com/questions/23609737/jquery-multiple-form-validation) – Heretic Monkey Feb 07 '19 at 13:47

7 Answers7

27

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 form tag.

$('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/


Quote OP:

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

Then your PHP loop is not constructed properly. Every id on a page must be unique or the HTML markup is invalid. You can simply use class instead 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.

Sparky
  • 98,165
  • 25
  • 199
  • 285
5

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

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

$('form.validateForm').each(function(key, form) {
    $(form).validate(); 
});
1
<!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>
Sandy
  • 11
  • 2
1
$('form.formID').each(function(key, form) { 
 $(this).validate({ 
    rules: {
         
        nick:{
          required: true,
          lettersonly: true,
          minlength: 3,
        },          
    },
    messages: {
        nick: {
        lettersonly:"Only alphabetical characters",
        required: "Enter your name",
        },
    },

submitHandler: function(form) {  
var nick = $("#nick", form).val();
  $.ajax({
      url: "REDIRECT URL HERE",
      method: "POST",
      dataType : 'json',
      data: {nick:nick},
      success: function (data) {
         
      }
   });  
 }                          
  });
});
Batuhan
  • 1,521
  • 12
  • 29
0

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.

Irshad Khan
  • 5,670
  • 2
  • 44
  • 39
  • 3
    That does not have anything to do with the jQuery Validate plugin, which is the method that the OP originally asked about... `$('#formID').validate()` – Sparky Oct 28 '18 at 16:43
  • This does nothing to answer the original question. – Ed DeGagne Jun 19 '19 at 14:17
0

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

$('form').submit(function (e) {
        e.preventDefault();
        var clikedForm = $(this);
        if (clikedForm.valid()) {
            alert('valid');
        } else {
            alert('not_valid');
        }
    });
Amaury
  • 126
  • 10
Hassan Tahir
  • 134
  • 9
0

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>
Devsainii
  • 497
  • 4
  • 6