19

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?

5
  • FYI, I have started a discussion about this question here. Commented May 19, 2012 at 15:46
  • There has been a confusion - that a typo resolved the issue. I deny that. I made the typo while writing the question, which was later corrected - but that was not the issue at all. Commented May 19, 2012 at 17:49
  • The problem is still persisting and I have absolutely no clue what's wrong with my implementation. Commented May 19, 2012 at 17:50
  • @AndrewWhitaker Thanks for the effort sir. Stackoverflow is really a valuable community ! Commented May 19, 2012 at 17:50
  • No problem--I have added an answer that will hopefully help. Commented May 19, 2012 at 17:56

4 Answers 4

18

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

$("form").validate()
$(yourElement).rules("add", {...})
Sign up to request clarification or add additional context in comments.

1 Comment

Just had the same problem, forgot to $("#formid").validate()
1

I think your code is more complicated than it needs to be. You should just have to call validate on document ready (assuming your form exists on document ready):

$(document).ready(function() {
    $(".val-req").addClass("required");
    $("#form_id").validate({
        errorElement: "span",
        errorClass: "val-error",
        validClass: "val-valid",
        errorPlacement: function(error, element) {
            $('#val-msg.' + $(element).attr('id')).html(error.html());
        },
        submitHandler: function () {
            this.submit();
        }
    });
});​

Example: http://jsfiddle.net/4vDGM/

You could also just add a class of required to required elements instead of adding them via JavaScript.

Another thing you could do is add rules in the rules object of validate's options:

$(document).ready(function() {
    $("#form_id").validate({
        rules: {
            myval: "required"
        },
        errorElement: "span",
        errorClass: "val-error",
        validClass: "val-valid",
        errorPlacement: function(error, element) {
            $('#val-msg.' + $(element).attr('id')).html(error.html());
        },
        submitHandler: function () {
            this.submit();
        }
    });
});​

Example: http://jsfiddle.net/GsXnJ/

5 Comments

Hm, but I have a custom submit method that submit values with ajax onclick event of a div button. Plus I don't want require class on my inputs, since I want it to be val-req, and similarly val-email and so on !
I can-not add inline rules in the validation method, since same code will be used to validate 20 forms with n number of fields. If I do that it would actually defeat the purpose.
@YugalJindle: Ah, okay. In that case you could just add an event handler for "click" on the button and submit the form that way.
I mean I have different forms with different submitting logics, but I will pass those submit methods as callback to this validate_form method, and want to keep the validation independent of the forms themselves.
I am looking to generalize the validation for multiple forms, that's why I need that dynamism.
1

I was trying to modify the rules on a form that already had validation being set up, but i found my $(document).ready(...) code was executing before the main form validation was set up, so adding a short setTimeout cured this issue for me - e.g.

setTimeout(function() {
    $(yourElement).rules("add", {...})
}, 100);

Comments

0

The culprit is the method delegate(), which does not check whether a validator exists:

function delegate(event) {
  var validator = $.data(this[0].form, "validator"),
  eventType = "on" + event.type.replace(/^validate/, "");
  // this fixes handling the deleted validator:
  if (!validator) return;
  validator.settings[eventType] && validator.settings[eventType].call(validator, this[0], event);
}

I was searching for a solution and found it in a blog post.

Source: http://devio.wordpress.com/2012/07/18/fixing-jquery-validation-with-changing-validators/

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.