Selvamani
Selvamani

Reputation: 7684

jQuery validate bootstrap plugin does not validate multiple forms

I have two forms in my HTML page. The validate function is working on only the first form of my HTML. The second form is not validated.

Here I make a Fiddle

Here is the validation code

$('form').validate({
  rules: {
    firstname: {
      minlength: 3,
      maxlength: 15,
      required: true
    },
    lastname: {
      minlength: 3,
      maxlength: 15,
      required: true
    }
  },
  highlight: function(element) {
    $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
  },
  unhighlight: function(element) {
    $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
  }
});

Upvotes: 3

Views: 2952

Answers (1)

Felix
Felix

Reputation: 38102

You can use .each() to loop through all <form> and use $(this) to target current validated form:

$('form').each(function () {
    $(this).validate({
        rules: {
            firstname: {
                minlength: 3,
                maxlength: 15,
                required: true
            },
            lastname: {
                minlength: 3,
                maxlength: 15,
                required: true
            }
        },
        highlight: function (element) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        },
        unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        }
    });
});

Updated Fiddle

Upvotes: 5

Related Questions