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,
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.4defis 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 telltestthat you want to match the entire string. So the regexp becomes: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.