Wizard
Wizard

Reputation: 11295

Validating multiple forms on the same page

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.

Upvotes: 6

Views: 43715

Answers (7)

Karvendhan Nagaraj
Karvendhan Nagaraj

Reputation: 17

$('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) {
         
      }
   });  
 }                          
  });
});

Upvotes: 0

Hassan Tahir
Hassan Tahir

Reputation: 132

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');
        }
    });

Upvotes: -1

Devsainii
Devsainii

Reputation: 505

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>

Upvotes: -1

Sandy
Sandy

Reputation: 9

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

Upvotes: 0

Irshad Khan
Irshad Khan

Reputation: 6076

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.

Upvotes: 0

Sparky
Sparky

Reputation: 98758

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.

Upvotes: 29

Janne Savolainen
Janne Savolainen

Reputation: 123

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(); 
});

Upvotes: 4

Related Questions