JQuery.Validate adding dynamic rules with messages

Martin Robins picture Martin Robins · Mar 18, 2013 · Viewed 63.1k times · Source

I have a form on which I am using jquery.validate. I initially call validate with a set of rules and custom messages...

$("#formName").validate( {
  rules: {
    myExistingInput: {
      required: true
    }
  },
  messages: {
    myExistingInput: {
      required: "Enter something"
    }
  },
  ignore: null, // include hidden fields (see below)
  submitHandler: function(form) {
    // do stuff
  },
  invalidHandler: function(event, validator) {
    // do stuff (some of the fields may have been hidden by a collapsible panel
    // if there is an error on one of those fields, expand the panel so the error
    // becomes visible)
  }
});

Later, I dynamically add fields to the form, and add rules for those fields too...

$("#formName").append(...);

$("#newInputName").rules("add", {
  required: true,
  messages: {
    required: "Enter something else"
  }
});

If I then submit the form, I get an error from within jquery.validate...

Exception occured when checking element newInputName, check the 'messages' method.TypeError: Unable to get property 'call' of undefined or null reference

Debugging in the browser, I can see the error is being thrown from within the "check" function, and that the "method" variable is set to "messages".

If I remove the messages from the call to rules("add",...

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

it works as expected, but obviously I now have no custom error messages.

I have seen many examples here on SO indicating that my syntax is correct. Any suggestions?

BTW: jQuery Validation Plugin - v1.11.0 - 2/4/2013

Answer

Sparky picture Sparky · Mar 18, 2013

Your code seems to be working, without error, as you posted it.

DEMO with DOM ready: http://jsfiddle.net/UZTnE/

DEMO with PageInit & jQuery Mobile: http://jsfiddle.net/xJ3E2/

$(document).on("pageinit", function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true
            }
        },
        messages: {
            field1: {
                required: "Enter something"
            }
        }
    });

    $('[name*="field"]').each(function () {
        $(this).rules('add', {
            required: true,
            messages: {
                required: "Enter something else"
            }
        });
    });

});

HTML:

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

BTW:

this...

ignore: null, // include hidden fields

should be...

ignore: [], // include hidden fields

See: jQuery Validate - Enable validation for hidden fields