1

I'm trying to validate a value against a regex to check if the number is either a decimal (with only 2 digits after the decimal point)/integer. The rest should be invalid.

I used the suggested regex here: Simple regular expression for a decimal with a precision of 2

But when I included it in my jquery regex function, it doesn't seem to work:

    function checkRegexp( o, regexp, n ) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass( "ui-state-error" );
            updateTips( n );
            return false;
        } else {
            return true;
        }
    }

bValid = bValid && checkRegexp( o_buy, /\d+(\.\d{1,2})?/, "Buy field can only contain numbers, no currency please" );

What am I doing wrong?

Thanks,

2
  • Where does bValid come from? If it is false, the check function will never be executed Commented Feb 26, 2011 at 10:38
  • bValid is true in this example. Commented Feb 26, 2011 at 10:41

3 Answers 3

3

You'll probably want to make that regex a little more precise, /^-?\d+(\.\d{1,2})?$/. Otherwise, it'll only test that the string contains a number.

Edit: updated the regex to cover negative numbers.

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

Comments

1

What do you mean by “it does not seem to work”? I've just tested your example, and it works as intended.

The sole problem is that you try to find the numeric pattern anywhere inside the string. It means that something like abc3.4def is accepted by your regexp.

However I suppose that you want the string to contain only a decimal number? Then you have to add the ^ and $ symbols at the start and at the end, to tell test that you want to match the entire string. So the regexp becomes:

/^\d+(\.\d{1,2})?$/

Was this your issue? If not, I may post a complete webpage that works OK for me, if it can be of any help to you.

Comments

0

I'm pretty sure you want to be using the following regex

/^\d+(\.\d{1,2})?$/

The problem with what you have is that {1,2} matches between 1 to 2 digits after the decimal, but doesn't fail if there is more. This is expected behavior.

Comments

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.