tags:

views:

22

answers:

1

Hey,

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

A: 

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.

Nick Craver
Thanks for the quick response, but that doesn't trigger the validation either.
Justin
@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.
Nick Craver
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
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
@Justin - Ah you got it before I did then....regex is definitely not my area of expertise, gad you got it working :)
Nick Craver