1

Yes, yet another question on regex with the JQuery validation plugin. I've followed all the examples I've found but for some reason cannot get this to validate only regex matches. It validates everything regardless of what regex I use (going for dollar amount under 100, optional $ and optional decimal up to hundredths place):

$.validator.addMethod("regexp", function (value, element) {
    return this.optional(element) || /^\$?\d{0,2}(\.\d{1,2}$)?/.test(value);
}, 'Please enter a valid USD format under $100, dollar sign optional.');

$("#formname").validate({
    debug: true,
    rules: {
        textbox: {
            required: true,
            regexp: true
        }
    }
});

JSFIDDLE DEMO

9
  • what is your validation criteria that you want to make ? e.g. what are you trying to filter out ? Commented Jul 5, 2013 at 1:47
  • Validate only input that matches the regex. Show the error message for everything else. Commented Jul 5, 2013 at 1:57
  • then why do you need a library for that ? you don't , just regex and events (keyup, keydown and change) is all what you need Commented Jul 5, 2013 at 1:59
  • I'm open to whatever works but this is part of a larger form that I'm validating. Other parts work using the plugin, I just extracted the part that's not working for some reason. It seems so easy just not sure if I'm missing something obvious. Commented Jul 5, 2013 at 2:00
  • the problem could be in the regex so I need you to explain to me what you want to do with it. so that I can re-build another one for you. Commented Jul 5, 2013 at 2:06

1 Answer 1

1

This should do

/^[$]?\d{1,2}([.]\d{1,2})?$/
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but the regex doesn't appear to be the problem, it's the plugin and/or the jquery. I plug your regex into jsfiddle.net/8fskm/6 and it does not require the input to match the regex. The input always validates, doesn't matter what regex pattern the rule is set to. It's like the plugin isn't even checking, so that indicates a problem with the jquery.
Just double checked it again (forgot to hit run after changes I guess) and I was wrong you are right, thanks!

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.