views:

5747

answers:

2

I setup the form validation using jQuery validation plug-in's validate method and I have a submit handler that modifies the input element's value (I use YUI editor and it needs saveHTML() call to copy the iframe's content to the textarea element.). When submitting the form, I want the validator to validate the form after executing my submit handler. But it doesn't execute my submit handler if it is registered after the validate call.

For example,

<form id="form1" action="/test">
    <input type="text" name="txt1" id="txt1" />
    <input type="submit" value="submit" />

$(document).ready(function() {
    $("#form1").submit(function() {
     $("#txt1").val("123456");
    });

    $("#form1").validate({
     rules: {
      txt1: {
       maxlength: 5
      }
     }
    });
});

The form is validated after my submit handler so submit is canceled.

$(document).ready(function() {
    $("#form1").validate({
     rules: {
      txt1: {
       maxlength: 5
      }
     }
    });

    $("#form1").submit(function() {
     $("#txt1").val("123456");
    });
});

However if I change the order the form is validated before my submit handler.

A: 

Try

$(document).ready(function() {
    $("#form1").submit(function() {
        $("#txt1").val("123456");

        $("#form1").validate({
            rules: {
                    txt1: {
                            maxlength: 5
                    }
            }
        });
    });
});

This way validation will be triggered by your submit event handler.

RaYell
A: 

You could use the beforeSubmit callback to set values:

$(function() {
    $('#form1').validate({
        rules: {
            txt1: { maxlength: 5 }
        },
        beforeSubmit: function(arr, $form, options) {
            $('#txt1').val('123456');
            return true;
        }
    });
});
Darin Dimitrov