21

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

5
  • 2
    What's your question? Please post your code here, not just as a fiddle link. Commented Jun 27, 2014 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. Commented Jun 27, 2014 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. Commented Jun 27, 2014 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). Commented Jun 27, 2014 at 13:03
  • 1
    @TrueBlueAussie, he's using the jQuery Validate plugin based on the OP stating, "the jQuery Validation plugin", his .validate() code, and the jquery-validate tag. And yes, it allows dynamic rule changes. Commented Jun 27, 2014 at 16:42

3 Answers 3

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.

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

7 Comments

thanks a lot for the elaborate explanation on usage of .validate()
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: jsfiddle.net/s6v45gka/1
@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.
@full.stack.ex, also, you can simply add/remove the required class; you do not need to use the .addClassRules() method at all. The .addClassRules() method is for constructing compound rules; the standard rules such as required can already be assigned by class all by themselves.
@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!
|
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();
    }
}

Comments

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

Comments

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.