jquery validation add inputs required dynamically

24,661

Solution 1

faced similar issue with it,

in fact what you'll notice is that validator is undefined at line 124, i.e. there is no validator instance associated with the form

if you check the validate method you see that if validator is undefined it will create a new one

var validator = $.data(this[0], 'validator');
        if ( validator ) {
            return validator;
        }

        // Add novalidate tag if HTML5.
        this.attr('novalidate', 'novalidate');

            //HERE it is creating a new one using the constructor   
        validator = new $.validator( options, this[0] );
        $.data(this[0], 'validator', validator);

Apparently the rules method assumes that validator is already there in the form object, so from my understanding, and since validate returns validator instance, you can call validate and then append your extra rules to the returned validator settings.rules object and re-run again which is not very practical.

The other solution would be to simply append the added rules to the initial rules object before calling validate

So in my case I wanted the input field to be validated as number however I didn't want Google Chrome to make it a number field (just try in Chrome to see what I mean, this had the issue of bypassing the type number validation in case the user entered manually, and in my case the user will most probably enter the number manually)

code example:

var customRule = {number: true};

//suppose populateValidateRules() fills your initial rules, which is my case at least
var validationRules =  populateValidateRules();

validationRules["rules"].fieldToBeDynamicallyModifiedForValidation= customRule;

$(formId).validate(validationRules);

Hope this helps

Solution 2

I'd gotten the same error message as well and realised that I should call the validate() on the form first before I call rules() on individual input fields. This behaviour is documented.

$('#form').validate({
  rules: {
    email: {
      email: true
    }
  }
});

$('#email').rules('add', {
  required: true
});

This may not be the answer to OP's problem, but I'm posting this to help anyone who searched jquery validation Cannot read property settings of undefined and clicked this page.

Thanks to the hint given by @nsawaya!

Share:
24,661
Andres
Author by

Andres

.NET programmer who has gone on a journey to learn PHP and JQuery. Still new but not a noob ;)

Updated on October 10, 2020

Comments

  • Andres
    Andres over 3 years

    I am currently using the bassistance jquery validation or the jqueryvalidation plugin(they renamed it) and I have it validating a form like so:

    if($.fn.validate) {
            $("#frmNewOrder").validate({
                rules: {
                    txtAmount: {
                        required: true,
                        digits: true
                    },
                    ddlAccount: {
                        required: true
                    },
                    ddlBank: {
                        required: true
                    }
                }
            });
        }
    

    Now depending on the amount I need to require or not an extra field a dropdownlist and depending on that dropdownlist another text input. so it's like:

     if($('#txtAmount').val() >= 10000){
         //add ddlReason required
     }
    
     if($('#ddlReason').val() == 'o'){
         //add txtReason required
     }
    

    I've tried adding the css class 'required' like the other fields but I take it if they are not inside the rules then it doesn't work? I've tried adding rules like this:

     $( "#ddlReason" ).rules( "add", {
            required: true});
    

    and that doesn't work either. any suggestions?

    EDIT: Here's the link to the jquery validate that I'm using. if I used rules outside it gives this error:

    Uncaught TypeError: Cannot read property 'settings' of undefined 
    

    on line 124:

    var settings = $.data(element.form, 'validator').settings;
    

    and using the suggestions I've seen in other places i've done this which is what causes the error:

    var defaultrules = {
        txtAmount: {
            required: true,
            digits: true
        }
    }
    
    if($.fn.validate) {
        $("#frmNewOrder").validate();
        addRules(defaultrules);
    }
    

    EDIT 2: here's the html markup, hope it helps.

    <form id="frmNewOrder" name="frmNewOrder" action="" method="post">
    <label>Amount</label>
    <input type="text" name="txtAmount" id="txtAmount" class="required" />
    <button id="calculate" type="button">Calculate</button>
    <div id="dvreason" style="display:none;">
        <select id="ddlReason" name="ddlReason">
             <option></option>
             <option value="i">Option 1</option>
             <option value="o">Other</option>
        </select>
        <div id="dvother" style="display:none">
           <label>Other reason</label>
           <input type="text" name="txtOther" id="txtOther" />
        </div>
    </div>
    <input type="submit" name="send" id="send" value="Send" />
    </form>
    
  • Ryanman
    Ryanman about 7 years
    Thank you so much, this was a huge help!