Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate() and Valid() methods undefined or do not work

I use jQuery validation in my MVC4 project with the necessary javascript files (jquery-1.9.1.js, jquery.validate.min.js and jquery.validate.unobtrusive.min.js) and configuration. What I want to do is to validate the form before submitting it. If the form is valid, a method will be called and then it will be submitted. If not, it will not be submitted and simply an alert will be displayed. I have followed the steps on Call JQuery Validate Plugin without submitting the form and lots of similar topics especially on the jQuery offical pages. But somehow, when executing the Validate() and Valid() method I encountered errors like undefined. I think the problem is related to Validate() method. I have tried different kind of jquery-1.x.x.js files, but the result is the same. How can I validate the form by using a similar method to the method below? Or anything else?

script type="text/javascript">
$(function () {
        $("#submitbtn").click(function () {
            var form = $("#myForm");
            form.validate();
            var isValid = form.valid();

            if (isValid) { //If there is no validation error
                alert('form is valid - not submitted');
            } 
            else {
                alert('form is not valid');                               
        }
    });
});

like image 437
Jack Avatar asked Mar 25 '26 19:03

Jack


1 Answers

I found the code was working perfectly fine however the ID of the element was not "myForm", have you tried ensuring that the ClientID attribute of the form is used rather than the ID?

$(function () {
    $("#submitbtn").click(function () {
        var form = $('#<%# myForm.ClientID %>');
        form.validate();
        var isValid = form.valid();
        if (isValid) { //If there is no validation error
            alert('form is valid - not submitted');
        } 
        else {
            alert('form is not valid');                               
        }
    });
});

I believe $("#myForm") wasn't returning the element as you would have expected (e.g. it was returning null or undefined as myForm didn't exist) hence form.validate() wouldn't exist.

like image 57
Wibble Avatar answered Mar 28 '26 08:03

Wibble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!