开发者

jQuery regex test

开发者 https://www.devze.com 2023-02-13 19:18 出处:网络
I\'m trying to validate a value against a regex to check if the number is eit开发者_Python百科her a decimal (with only 2 digits after the decimal point)/integer. The rest should be invalid.

I'm trying to validate a value against a regex to check if the number is eit开发者_Python百科her 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,


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消