3

I have a form that needs to be validated but it does not have a submit button. So to get the validation done, I followed the example on http://docs.jquery.com/Plugins/Validation/valid

which tells to call .valid() function. So i added the following code which worked fine:

            $(".getcars").click(function() {
                valid = $("#form1").valid();
                if(valid){
                    ajaxCall();
                }

            }); 

Now I want to add more rules to the validation field , so i tried

jQuery.validator.addMethod("lettersandnumonly", function(value, element) {
                return this.optional(element) || /^[0-9A-Za-z]+$/i.test(value);
                    }, "Letters and numbers only ");
jQuery.validator.addMethod("nowhitespace", function(value, element) {
                return this.optional(element) || /^\S+$/i.test(value);
            }, "No white space please"); 

            $(".getcars").click(function() {
                valid = $("#form1").valid(
                {
                rules: {
                    postal_code: {
                        maxlength: 6,
                        lettersandnumonly: true,
                        nowhitespace: true
                    }
                }
            });
                if(valid){
                    ajaxCall();
                }

            });

but this is not working. Can anyone tell me what I am doing wrong while adding the rule?

1
  • btw , the field I am trying to validate is <div class="label">Please enter your Postal Code or a part of it!</div> <input type="text" id="postal_code" name="postal_code" /> Commented Oct 21, 2011 at 23:45

1 Answer 1

1

rule definitions go in the initial call to validate(). Since valid() only works on forms that have had validate() called on them, I'm assuming you have a line in the code somewhere calling validate():

$("#form1").validate();

All you should have to do is move your rule definitions into that initial call:

$("#form1").validate({
    rules: {
        postal_code: {
            maxlength: 6,
            lettersandnumonly: true,
            nowhitespace: true
        }
    }
});

... And then call .valid() later like you were doing initially:

$(".getcars").click(function() {
    valid = $("#form1").valid();
    if(valid) {
        ajaxCall();
    }
}); 
Sign up to request clarification or add additional context in comments.

Comments

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.