1

I'm trying to add a jQuery validator rule dynamically and it's not working. It doesn't throw any errors but doesn't trigger the validation.

Here's the js:

$(document).ready(function () {

    $.validator.addMethod("TIME", function (value, element) {
        var re = new RegExp(regexp);
        console.debug("Validating " + value);
        return this.optional(element) || re.test("^*(1[0-2]|[1-9]):[0-5][0-9] *(a|p|A|P)(m|M)*$").test(value);
    }, "Time is invalid: Please enter a valid time.");

$("input[id *= '_timepicker']").rules("add", "TIME");

});

Any idea what's wrong?

EDIT:

Now I get an error: invalid quantifier *(1[0-2]|[1-9]):[0-5][0-9] (a|p|A|P)(m|M)$

Here's the relevant js:

rules:{"special.Hours.FridayHours1.close":{ regExp: /^*(1[0-2]|[1-9]):[0-5][0-9] *(a|p|A|P)(m|M)*$/ }

Here's the complete validate function:

http://pastebin.com/YRday2Mv

2 Answers 2

3

Your syntax is off just a bit, you need to pass it an object instead of a string, like this:

$("input[id*='_timepicker']").rules("add", {"TIME": true });

You can find the .rules() documentation with more examples here.

5
  • Thanks for the quick response, but that doesn't trigger the validation either.
    – Justin
    Jun 4, 2010 at 2:54
  • 1
    @Justin - This won't trigger it, you'll need to run .valid() to actually validate, this just adds the rule, when are you expecting it to validate? Also, have you run the .validate() method prior to this? it must be called first, this just adds additonal rules. Jun 4, 2010 at 2:56
  • I never call .valid(), however I tried adding the rule to my .validate() function instead of dynamically adding the rule and now I get an invalid quantifier error.
    – Justin
    Jun 4, 2010 at 3:18
  • I got it working by changing the regex to this: /^\*(1[0-2]|[1-9]):[0-5][0-9] \*(a|p|A|P)(m|M)*$/
    – Justin
    Jun 4, 2010 at 3:26
  • @Justin - Ah you got it before I did then....regex is definitely not my area of expertise, gad you got it working :) Jun 4, 2010 at 3:27
-1
$(function() {
      $('#order_form_id').validate();
      $("input[id*='_quantity']").each(function () {$(this).rules("add", {required:true,zznum:true});})
    });
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.