user1496786
user1496786

Reputation: 21

jQuery Validation failing unless call $('#form').valid()

I have a large application that is using a lot of jQuery and I ran across one page today in testing that will not validate correctly. I have saved a copy of the page off and deleted all other jQuery except the code to validate the single field that I am having trouble with.

In the following code, it works perfectly:

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnSave').click(function (e) { validateRegisterForm(e); });
    });

    function validateRegisterForm(e) {

        $('#EMasterForm').validate();
        alert('validation result is : '+ $('#EmasterForm').valid());
        $('#txtMaxCommute').rules                 
            ('add', { 
                required: true, 
                minlength: 2,
            }); // end of rules(add) function call

            if ($('#EmasterForm').valid() == false) {
                e.preventDefault();
        }
    }


</script>

But if I comment out the alert, it does not work. And the alert always shows a value of 'true'.

This seems like a dumb question to me. But I have 50 other pages validating like clockwork. And I am coming up short on this one. We are using jquery everywhere for all sorts of operations. But this one page will not work.

Can anyone possibly shed any light on why the alert would make it work? I am happy to be chastised by whomever answers this :)

Thank you in advance!

Upvotes: 1

Views: 279

Answers (2)

Govind Totla
Govind Totla

Reputation: 1178

jQuery validate function and all other functions need to initialize on DOM ready. as stated above $('#YOUR_FORM_ID').validate(); should be called in Document ready. Check out a demo, it will surely help you.

http://jquery.bassistance.de/validate/demo/

Upvotes: 0

gaurang171
gaurang171

Reputation: 9080

I assume that you have btnSave as submit button.

You are trying to bind validate onclik of the submit button. so at the time of click submit event is not doing any validation thats the reason you need to call .valid() again.

I would suggest just move $('#EMasterForm').validate(); and Rules Related code out side of the click and you dont need to bind anything on click event.

just do following and you are done.

 $(document).ready(function () {
        $('#EMasterForm').validate();
        $('#txtMaxCommute').rules                 
            ('add', { 
                required: true, 
                minlength: 2,
            }); // end of rules(add) function call
 })

Upvotes: 2

Related Questions