Gabriel Muñumel
Gabriel Muñumel

Reputation: 1876

Jquery validation is not working. Jquery - Javascript

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;
    }

Upvotes: 0

Views: 517

Answers (2)

Icarus
Icarus

Reputation: 63956

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

if($('#ReqCreateForm').valid())
{
    //then do your thing
}

Upvotes: 1

pollirrata
pollirrata

Reputation: 5286

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)

Upvotes: 0

Related Questions