5

I am using jQuery validate for validate an input. My code:

 $('#button').click( function() {       
    $("#form").validate({              
        rules: {
            phone: {
                required: true,
                number: true,
                rangelength: [7, 14]
            }
        }
    }); 
});

And the HTML:

<form id="form" name="form" method="post" action="">
 <input id="phone" name="phone" class="required" type="text" />
 <div class="button" id="send_b">Send</div>
 </form>

This code is not working. If I add this line of jQuery

$("#form").submit();  

inside the click event it works. But I don't want to submit the form so I want just to make the validation on click.

Does anyone know how to do this?

2
  • Give more detail on "not working." What isn't it doing that you expect it to? Commented Sep 16, 2011 at 13:31
  • IIRC validate() doesn't do the validation, it sets up the validation for the submit. Poke around the code to see if it can be short-circuited, or if there's a method you can call that actually does just the validation. Commented Sep 16, 2011 at 13:34

3 Answers 3

14

Just add .form() to manually trigger the validation immediately (the default behavior waits for a submit event):

$('#button').click( function() {       
  $("#form").validate({              
    rules: {
      phone: {
        required: true,
        number: true,
        rangelength: [7, 14]
      }
    }
  }).form(); 
});
Sign up to request clarification or add additional context in comments.

Comments

0

Your code is binding a function to the click event of a button. What you're doing is saying "when this button is clicked, apply form validation to the form".

This is the incorrect way to use the validation plugin (I'm assuming you're using this validation plugin). Instead, you just execute the validation() method directly onto the form element; the plugin takes care of the submit event.

So, get rid of the click event binding.

1 Comment

I just came across an issue where I am validating a single input box and the value is a parameter to a link. But I think you are right it will validate onclick automatically.
0

Use form method form() method with your click event

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.