20

I have one form with around 50 fields and two submit buttons, "SAVE" and "SAVE & SUBMIT". If the user clicks "SAVE", then validate only some values, eg. field1, field2. When user clicks "SAVE & SUBMIT" button, it should validate all 50 fields and submit.

<form id="myform">
    <input type="text" name="field1" />
    <br/>
    <input type="text" name="field2" />
    <br/>
    <input type="text" name="field3" />
    <br/>
    <input type="text" name="field4" />
    <br/>
    <input type="submit" id="button1" value="Save" />
    <input type="submit" id="button2" value="Submit" />
</form>


$(document).ready(function () {

    $('#button1').click(function(){          
        $("#myform").validate({             
            rules: {
                field1: {
                    required: true                         
                },
                field2: {
                    required: true                        
                }
            },
            submitHandler: function (form) { // for demo    
                alert("data saved");
            }
        });
    }); 

    $('#button2').click(function(){
        $("#myform").validate({             
            rules: {
                field1: {
                    required: true                          
                },
                field2: {
                    required: true                           
                },
                field3: {
                    required: true                         
                },
                field4: {
                    required: true                          
                }
            },
            submitHandler: function (form) { // for demo
                alert("data submited");
            }
        });
    });

});

I have created jsfiddle for this: example test

Sparky
  • 98,165
  • 25
  • 199
  • 285
Ajit Singh
  • 1,132
  • 1
  • 13
  • 24
  • 2
    What's your question? Please post your code here, not just as a fiddle link. – Barmar Jun 27 '14 at 11:20
  • `validate` is designed to be applied once to a form. Whichever button you press first is setting the validation from then onwards. You would need to figure out how to strip existing validation from all fields before applying `validate` again. – iCollect.it Ltd Jun 27 '14 at 11:22
  • @Barmar as i said i have 50 fields it i post all my code it will be very log question. there is no point to down voting this question. all the test i have done on jsfiddle. – Ajit Singh Jun 27 '14 at 11:48
  • Which `validate` are you using (download page please)? Some validation plugins allow you to add and remove rules dynamically (but I have a feeling yours is not one of those). – iCollect.it Ltd Jun 27 '14 at 13:03
  • 1
    @TrueBlueAussie, he's using [the jQuery Validate plugin](http://jqueryvalidation.org) based on the OP stating, _"the jQuery Validation plugin"_, his `.validate()` code, and the [tag:jquery-validate] tag. And yes, it allows dynamic rule changes. – Sparky Jun 27 '14 at 16:42

3 Answers3

33

Your code...

$('#button1').click(function(){             
    $("#myform").validate({
        ....
    });             
}); 

$('#button2').click(function(){
    $("#myform").validate({
        ....
    });
});

You absolutely cannot do this:

1) You cannot call the .validate() method more than once on the same form. Any subsequent calls are always ignored.

2) You should not put the .validate() method inside of a click handler. The .validate() method is the initialization method of the plugin and only gets called once within a DOM ready event handler. After proper initialization, the submit button click is captured automatically by the plugin.


HTML Markup and Click Handlers:

This plugin also automatically captures the click of any input type="submit" and button type="submit" elements and initiates validation/submission.

So if you need to control what happens for two different buttons, then you first need to change your buttons into input type="button" or button type="button" elements.

Then you can use click() handlers to dynamically change the rules with the .rules() methods as per which button was clicked. See the .rules() methods documentation.

Use .submit() to programmatically submit. In other words, this will trigger a validation test and attempt to submit the form IF valid... same as if you had a submit button.

Use .valid() to programmatically test the form. In other words, this will trigger a validation test but will NOT submit the form IF valid.


Example:

$(document).ready(function () {

    $('#myform').validate({  // initialize the plugin on your form
        // options, rules and/or callbacks
    });

    //  IMPORTANT:  buttons are NOT type="submit"

    $('#button1').on('click', function(){  // capture the click           
        $('#myfield').rules('add', {  // dynamically declare the rules
            required: true,
            email: true
        });
        $('#myOtherField').rules('remove'); // remove the other rules.
        // another '.rules()' call, etc.
        $('#myform').valid();  // trigger the validation & do NOT submit        
    }); 

    $('#button2').on('click', function(){  // capture the click
        $('#myOtherField').rules('add', {  // dynamically declare the rules
            required: true,
            digits: true
        });
        $('#myfield').rules('remove'); // remove the other rules.
        // another '.rules()' call, etc.
        $('#myform').submit();  // trigger the validation & submit     
    });

});

Working DEMO: http://jsfiddle.net/Kt93M/

The demo is simply your original jsFiddle with these principles applied.

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • thanks a lot for the elaborate explanation on usage of .validate() – Ankit Aggarwal Apr 09 '15 at 07:43
  • 2
    An alternative: you CAN use submit buttons, e.g., so that the server knows which one was clicked. This is also a more declarative solution: use jQuery.validator.addClassRules(), add or remove a certain class in response to clicks. Here's @Sparky 's fiddle updated: http://jsfiddle.net/s6v45gka/1 – full.stack.ex Jan 29 '16 at 18:01
  • @full.stack.ex, It does not matter if you manipulate classes or use the `.rules()` method... in your example, both buttons are submitting the form after validation. However, the OP did NOT want to submit with both buttons. – Sparky Jan 29 '16 at 18:31
  • @full.stack.ex, [also, you can simply add/remove the `required` class; you do not need to use the `.addClassRules()` method at all](http://jsfiddle.net/s6v45gka/2/). The `.addClassRules()` method is for constructing *compound* rules; the standard rules such as `required` can already be assigned by class all by themselves. – Sparky Jan 29 '16 at 18:36
  • @Sparky , you are right. Your solution is 100% correct. We've just used your answer and added the "declarative" approach to submit with 2 buttons. Thought someone might need the same. Thank you! – full.stack.ex Jan 29 '16 at 18:37
  • @full.stack.ex, ok, I see. Check out my very last comment; it might help you make it more efficient. – Sparky Jan 29 '16 at 18:39
  • @Sparky , thank you again for your findings. In fact, we do have compound rules. I get it: it may be too far from the original question. You are right, in the simplest case, the required class would do the job. – full.stack.ex Jan 29 '16 at 18:47
0

If you will use the same validation, maybe you should this code:

Insert an hidden action, to say the validation the method to use after we click the button

<input type="hidden" id="action" name="action">

Then in your submit Handler:

submitHandler: function (form, event) {
    var action = $("#formPagoContratista #action").val();
    if (action === "action_1") {
        firstFunction();
    }else if (action === "action_2") {
        secondFunction();
    }
}
0

If you have the below two buttons:

<div class="form-group text-right my-5 ">
  <input type="submit" name="save" class="btn btn-bg col-sm-2 form-control" value="Save">

You can validate and submit based on the two buttons: Save sends with ajax and no reload. Next button saves and redirects to next page.

$('form').validate({
            submitHandler: function(form, e) {
              var button = $(":focus", this);

              var name = button.context.submitButton.defaultValue;
              console.log(name);
              if(name == "Save"){
                $(form).ajaxSubmit();
              }else{
                form.submit();
              }
            }
          });

checkout this post: https://stackoverflow.com/a/61423083/1004799

rarejewel
  • 26
  • 1
  • 4