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

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

Thanks for your answer. I found a simply way to do this. Cheers.

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.