Jquery validation is not working. Jquery - Javascript

Go To StackoverFlow.com

0

My problem is with the validation of my form using Jquery. My validation was working good with the validate function only but then I added the submit option and the validation is not taking place. I would like to validate my form and then execute the submit.

$(document).ready(function () {
    $('#ReqCreateForm').validate({
         invalidHandler: function (e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = errors == 1
                ? 'Missing 1 field'
                : 'Missing fields';
                $("div.error span").html(message);
                $("div.error").show();
            } else {
                $("div.error").hide();
            }
        },
        onkeyup: false,
        highlight: function (element) {
            $(element).addClass('error');
        }, unhighlight: function (element) {
            $(element).removeClass('error');
        }
    });

    $('#ReqCreateForm').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                alert("All Great!");
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
            }
        });
        return false;
    });
});

Thanks in advanced.

Solution:

The solution was very simply. Added the following code to my submit option, before $.ajax.

  if (!$(this).valid()) {
         return false;
    }
2012-04-04 18:35
by Gabriel Muñumel


1

You have to invoke the valid function on the click handler of the submit button as so:

if($('#ReqCreateForm').valid())
{
    //then do your thing
}
2012-04-04 18:41
by Icarus
Your answer show me the way. Thank you - Gabriel Muñumel 2012-04-04 19:05


0

I use this plugin for submiting the form using Ajax. It has an event called onbeforesubmit, where you can call the validations without a problem. Maybe you wanna try it. In your case, you'll need to catch the event befor submitting data to the ajax call in order to validate it (in case you don't wanna use the plugin I suggested)

2012-04-04 18:38
by pollirrata
Thanks for your answer. I found a simply way to do this. Cheers - Gabriel Muñumel 2012-04-04 19:04
Ads