25

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

Sparky
  • 98,165
  • 25
  • 199
  • 285
Martin Robins
  • 6,033
  • 10
  • 58
  • 95
  • FYI: Also being used in combination with jquery.mobile. $("#formName").validate({...}) is being called from $(document).on("pageinit",...) whereas the dynamic fields are added on the click of a button. Don't know if that matters? – Martin Robins Mar 18 '13 at 17:12
  • Please edit your OP to include that info. – Sparky Mar 18 '13 at 17:27
  • @Sparky: you are right, fixed in issue #670. I have replicated that fix into my copy until such time as a new version is officially released. Also fixed in issue #674, but I do not know which version will make it to release. Missing code in normalizeRules between versions 10 and 11 identified in #674 (restoring this missing code fixes the problem too), but funnily enough the fix suggested in #674 is not to restore the code and also differs from #670. – Martin Robins Mar 18 '13 at 17:33
  • I'm not so sure that this is a bug... you can see my jsFiddle below is working fine with jQ Mobile. – Sparky Mar 18 '13 at 17:49

3 Answers3

35

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

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Thanks for the pointer on ignore:[]; still not sure about the original problem though; I have compared the jquery.validate.min I have with the version on the asp.net cdn and they are identical. I will look into this more tomorrow and get back to you. – Martin Robins Mar 19 '13 at 00:37
  • 2
    @MartinRobins, just open http://jsfiddle.net/xJ3E2/show/ in your browser and "view source". Compare it to your code. – Sparky Mar 19 '13 at 00:47
  • I have updated to reflect my code. DOM version (http://jsfiddle.net/UZTnE/2/) no longer works; Cannot get JQM version to run at all. Different problem though. – Martin Robins Mar 19 '13 at 09:36
  • 2
    @MartinRobins: Because you broke it. You are trying to select `$("#field2")` where one does not exist. `#field2` is looking for `id="field2"`, **not** `name="field2"`. Try this one: http://jsfiddle.net/UZTnE/3/ – Sparky Mar 19 '13 at 14:22
  • I can see what you mean; I was simply trying to update the code to represent what I am trying to achieve and did not notice that you had not provided id's in you example. I will try and find time to provide a proper update that shows the real error, but as I originally stated I am not the only person to report this and multiple fix attempts have already been made to the github source - one of which when applied to the latest release copy resolves my problem. – Martin Robins Mar 24 '13 at 11:42
  • @MartinRobins, yes, without a doubt, there were/are issues with the plugin when using the `rules('add')` method with the `messages` option. However, these bugs are not present as you originally posted your code here in your OP... and that's all I can say. I wish you luck. – Sparky Mar 24 '13 at 14:43
  • Just upgraded to 1.11.1 which fixed the problem with the complaining of the messages in custom rules('add'), but the onclick: false to prevent auto-validation on click is not working for these custom methods. – bcm May 30 '13 at 03:19
  • @bcm, if you read the documentation, you'll notice that `onclick: false` is only for disabling the validation test when clicking on `radio` and `checkbox` inputs. – Sparky May 30 '13 at 03:39
  • Fantastic, this helped me a bunch. – Ed DeGagne Jan 14 '15 at 03:52
  • How can I make this work with a custom rule? The custom rule doesn't execute – vladimir.gorea Oct 27 '17 at 12:34
10

$(document).ready(function(){
  $("#controlId").rules("add", {
     required : true,
     messages : { required : 'field is required.' }
  });
});
0

as an answer to this old issue, I do like this to get the meassges inside the rules object.

After you have added the rules you can add messages like this:

var inputRules = $('input').rules();
inputRules.messages = {required: 'your message'};

enter image description here

Good luck!

Eagle_one
  • 426
  • 4
  • 15