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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the quick response, but that doesn't trigger the validation either.
@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.
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.
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 - Ah you got it before I did then....regex is definitely not my area of expertise, gad you got it working :)
-1
$(function() {
      $('#order_form_id').validate();
      $("input[id*='_quantity']").each(function () {$(this).rules("add", {required:true,zznum:true});})
    });

1 Comment

Please try to avoid just dumping code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. Please edit your answer to include clarification, context and try to mention any limitations, assumptions or simplifications in your answer.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.