2

I have a situation where validating a HTML form with jQuery Validation Plugin 1.9.0. (I'm using jQuery 1.6.4). If the form is filled out correctly after the page is loaded the validation takes place on submit. The validation gives a success message, but it doesn't trigger the submitHandler. It only triggers the submitHandler if you press the submit button again.

I created a simulation on http://jsfiddle.net/peterph/Hv3xz/1/ to illustrate the problem. Can anyone tell me how I can fix this problem?

<form method="post" id="form">
    <input id="E_Mail" name="E_mail" title="E_mail" required="required" /><br />
    <input class="submit" type="submit" value="Send"/>
</form>

<script>
    jQuery(function($) {
        $("#form").submit(function(e) {
            var $form = $(this);
            alert('Start Validation');
            $form.validate({
                debug: false,
                focusInvalid: false,
                onfocusout: false,
                onkeyup: false,
                onclick: false,
                rules:
                {
                    E_mail: {required:true, email:true },
                },
                success: function(label) {
                    alert('succes:' + label);
                },
                submitHandler: function(form){
                    alert('start submitHandler');
                    postContent('test');
                    alert('end submitHandler');
                },
                invalidHandler: function(form, validator) {
                    alert('invalidHandler');
                },
            }).form();
            alert('end Validation');
            e.preventDefault();
        });
    });

    function postContent(postData){
        alert('postcontent: ' + postData);
    }
</script>
Ciarán Bruen
  • 5,221
  • 13
  • 59
  • 69

1 Answers1

2

validate is not called until you submit the form. The first time you hit submit, validate has not been applied to the form. The second time it has.

You should move the call to validate outside of the submit handler:

jQuery(function ($) {
    $("#form").validate({
        debug: false,
        focusInvalid: false,
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        rules:
        {
            E_mail: {required:true, email:true },
        },
        success: function(label) {
            alert('succes:' + label);
        },
        submitHandler: function(form){
            alert('start submitHandler');
            postContent('test');
            alert('end submitHandler');
        },
        invalidHandler: function(form, validator) {
            alert('invalidHandler');
        },
    });
});

And everything should work fine.

Updated Example: http://jsfiddle.net/8r47E/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307