5

I have a simple page with a form and a button outside the form. I am trying to validate the form on the button click. I have added the rules for validation of the form on the document.onready function. However the form is not getting validated.

HTML

<form id="form1" method="post" action="">
  <div>
    <input name="Name" id="name1" data-errorclass="error-name"/>
  </div>
  <input type="submit" id="name_id" value="Save"/>
</form>

JS

$(document).ready(function () {
   $("#name_id").click(function() {
     alert("called");
     $('.form1').validate({
       rules: {
        'Name' : {
            required: true
         }

       },
       messages: {
        'Name' : {
            required: 'Name is  required'
         }
       },
       errorClass: 'error-name',
       errorPlacement: function(err, element) {
        err.insertBefore(element);
        },        
     });
   });
});

fiddle

3
  • did you try doing $('#form1').submit(function() {....}); Commented Oct 22, 2013 at 7:03
  • instead of $("#name_id").click(function() { Commented Oct 22, 2013 at 7:04
  • By fixing the code in your question, the answer no longer makes any sense. I rolled it back so that readers can understand why the accepted answer works. Commented Oct 22, 2013 at 19:40

2 Answers 2

9

As already stated, the original code was targeting a class, .form1, while the actual form contained id="form1". Fixing the selector to target the id will quickly solve this.

$('#form1`).validate({...

Despite an answer already being posted, I feel the need to also post some important notes regarding some common misconceptions about this plugin.

The .validate() method is only used for plugin initialization, not a method for testing the validity. So putting .validate() inside a click handler makes no sense. .validate() only needs to be called one time, so being called repeatedly upon every click is redundant and unnecessary.

As long as the submit button is inside the <form> tags, there is no need for a click handler as this is automatically captured by the plugin. See: http://jsfiddle.net/B5mVh/6/

If the button is outside of the <form>, you can use the .valid() method to test the form's validity.

$(document).ready(function () {

    $('#form1').validate({  // <-- INITIALIZE plugin on your form
        // your rules & options      
    });

    // For button OUTSIDE of form tags
    $("#name_id").click(function() {
        if ($('#form1').valid()) {
            alert("form is valid");
        } else {
            alert("form is invalid");
        }
    });

});

DEMO: http://jsfiddle.net/B5mVh/4/

However, in your original code, the button is inside the form, so as explained before, there's no need for a click handler at all. But if you want to run some code upon the click event, use the submitHandler (when valid) and invalidHandler (when invalid) callback functions.

$(document).ready(function () {

    $('#form1').validate({  // <-- INITIALIZE plugin on your form
        // your rules & options,
        submitHandler: function(form) {
             alert("form is valid");
             return false;
        },
        invalidHandler: function() {
            alert("form is invalid");
        }
    });

});

DEMO: http://jsfiddle.net/B5mVh/5/

Of course, you don't have to use these optional callback functions. The plugin works perfectly fine without them as shown before:

DEMO: http://jsfiddle.net/B5mVh/6/

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for clarifying. May I point out that the documentation jqueryvalidation.org/validate is terrible. It says "validate - validates the selected form". doh! seriously? that is wrong, or meaningless at best. What it should say is "validate - will attach an event handler to the form so that it will get validated at a later time, whenever the submit button is pressed."
@JohnHenckel, that's not accurate either, because the .validate() method does way more, and validation is automatically triggered by other events besides the click of the submit button. You know the documentation for this free plugin is available on GitHub. In other words, instead of complaining, you can submit your contributions, suggestions, additions or corrections to the developer for inclusion.
@Sparky, I could, but why don't you do it? I bet you'd do a much better job that I would. Just copy-paste a few sentences from your answer to the link I posted. And thanks again.
@JohnHenckel, thanks... I've made a few minor improvements to the docs in the past. However, for future reference, the SO Tag Wiki page is also very informative.
3

In jQuery's validate() function you call it on a form with the class .form1, you should name this correctly to the corresponding ID #form1.

This should solve your issue.

6 Comments

@Sidney Liebrand -No its impossible. If I added like that it would affect other functionalities.
It's always abit messy working with ID's and classes a common mistake that also happened to me plenty of times :)
Sam: How is it impossible? you are targeting a nonexistent class
An ID should be unique, if you have multiple same ID's you should change this to a class, otherwise rename your ID to something unique.
@BarryChapman, he mentioned it will affect multiple items by using that ID, hence I mentioned the above, where he would suggestively change his ID to something unique
|

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.