Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery validation - Error on adding rules to input element?

I am trying to implement Jquery validation with http://docs.jquery.com/Plugins/Validation :

My design plan:

  • My input element:

    <form action="submit.php" id="form_id">
      <input type="text" class="val-req" id="my_input" name="myval" />
      <input type="button" onclick="validate_form('form_id', function() { $('#form_id').submit(); })" />
      <span id="val-msg" class="my_input"></span>
    </form>
    
  • Then, on dom ready:

      $(document).ready(function() {
                          $('.val-req').rules('add', {required:true});
                       });
    
  • Validate method:

     function validate_form(form_id, callback) {
           var form = $('#'+form_id);
           $('.val-req').each(function() {$(this).rules('add', {required:true});});
           $(form).validate({
                    errorElement: "span",
                    errorClass:   "val-error",
                    validClass:   "val-valid",
                    errorPlacement: function(error, element) {
                                          $('#val-msg.'+$(element).attr('id')).innerHTML(error.html());
                                   },
                    submitHandler: callback
           });
     }
    

As per my expectations, it should display error message in the place holder span in the form.

But, Problem

Error on Chrome-Console: Uncaught TypeError: Cannot read property 'settings' of undefined

It is also giving error on other browsers. Then, I tried to figure-out the problem and found:

 $('.val-req').rules('add', {required:true});   # This is causing the error

As, per my understanding and documentation -> This should be correct.

Why would this cause the TypeError and what can I do to resolve it?

like image 254
Yugal Jindle Avatar asked May 18 '12 10:05

Yugal Jindle


1 Answers

You have to add the rules after you call the validate plugin in the form element:

$("form").validate()
$(yourElement).rules("add", {...})
like image 195
holamon Avatar answered Sep 22 '22 22:09

holamon