2

I have two forms on one page with a starting and closing <form></form> tag for each form. I m validating it with JQuery Validate Plugin. I have to validate both forms with one single button. The problem is that validation of both forms required a separate button for each form which is not required. the code is given below:-

$(document).ready(function(){
 $('.formValidate').each(function() {   // <- selects every <form> on page
        $(this).validate({

    rules: {
         orderno: { //placed at first form
            required: true,
            minlength: 5
        },customername: { //placed at second form
            required: true,
            minlength: 5
        }
    },
    //For custom messages
    messages: {

        order:{
            required: "Enter a Order No",
            minlength: "Enter at least 5 characters"
        },customername:{
            required: "Enter a username",
            minlength: "Enter at least 5 characters"
        }

    },
    errorElement : 'div',
    errorPlacement: function(error, element) {
      var placement = $(element).data('error');
      if (placement) {
        $(placement).append(error)
      } else {
        error.insertAfter(element);
      }
    },
    submitHandler: function() { 
        console.log("Order submitted!"); 
    }


 });
 });


}); //end readyfunction

HTML is as given below:-

<form class="formValidate" id="tstordform" method="get" action="">
    <div class="row">
         <div class="input-field col s12">
             <i class="mdi-image-tag-faces prefix"></i>
             <input  id="orderno" name="orderno" type="text" data-error=".errorTxt1">
             <label for="orderno">Order No.*</label>
             <div class="errorTxt1"></div>
          </div>
     </div>
</form>

<form class="formValidate" id="cstdataform" method="get" action="">
    <div class="row">
        <div class="input-field col s12">
            <i class="mdi-action-account-circle prefix"></i>
            <input id="customername" name="customername" type="text" data-error=".errorTxt6">
            <label for="customername">Customer Name</label>
            <div class="errorTxt6"></div>
        </div>

        <div class="input-field col s3">
            <button id="validateboth" class="btn waves-effect waves-light center cyan submit" type="submit" name="action">Save Order
                <i class="mdi-content-send right"></i>
            </button>
        </div>
    </div>
</form>

Kindly help me!

2
  • Could you use this for your first line: $(form).each(function() { Commented Jan 19, 2017 at 22:59
  • if i use form tag then the page is reloaded and form is submitted. Both forms have different ids and same class. Commented Jan 19, 2017 at 23:07

1 Answer 1

3

The problem is that validation of both forms required a separate button for each form which is not required.

Not really sure what you mean, so showing your desired HTML markup would be helpful.

I have to validate both forms with one single button.

Remove all buttons from both forms and put a single button outside of them.

Then write a handler that submits both forms at the same time. This will trigger validation on both...

$('#submitboth').on('click', function(e) {
    e.preventDefault();
    $('[id^="myform"]').submit();
});

DEMO 1: jsfiddle.net/293ps7k9/

The downside to this is that one or both forms will submit if/when there are no errors.


Alternatively, you can leave the submit buttons on each form and just create a third button and handler that triggers a validation test on both.

$('#validateboth').on('click', function(e) {
    e.preventDefault();
    $('[id^="myform"]').each(function() {
        $(this).valid();  // <- validation test only
    });
});

DEMO 2: jsfiddle.net/tupn779c/


EDIT:

I have to first validate both forms and then submit the data of both forms via a single function call through ajax.

Your single comment explains it better than everything in your OP. Although, functionally, this is absolutely no different than putting everything inside of a single form container.

The solution is practically the same as the two above:

  1. Capture the click event of the single submit button contained outside of the form containers. (Otherwise, you can use a type="button" and put it anywhere you want.)

  2. Loop through the two forms looking for errors via the .valid() method.

  3. Then when both forms pass validation, trigger a .submit() for both forms. This will in turn trigger the submitHandler functions on each form where your Ajax is located. (Ajax must go inside the submitHandler callback for each instance of .validate())

See Final DEMO below.

$('#validateboth').on('click', function(e) {
    e.preventDefault();
    var forms = $('[id^="myform"]');
    forms.each(function() {
        $(this).valid();
    });
    if ($('#myform1').valid() && $('#myform2').valid()) {
        forms.submit();
    }
});

Final DEMO: jsfiddle.net/qtcs7uwe/

Sign up to request clarification or add additional context in comments.

5 Comments

Its not working. if i use first solution then form is not validated and submitted.
I have to first validate both forms and then submit the data of both forms via a single function call through ajax. I have also added the html code above.
@user2782882, you simply have to tweak the methods I've already shown you. See my third demo in the edited answer: jsfiddle.net/qtcs7uwe
Your solution is validating both forms but it does not show error on myform1. I.e. If i place input type button near first form then it shows error on first form and not on 2nd form. So it shows error on that form where i put the submit button.
@user2782882, did you make your button a type="button" as I instructed in my step #1? See: jsfiddle.net/qtcs7uwe/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.