Reputation: 31
Hi I need help with an input. I need to make a regular expression that filter it on keypress.
The input will have a number with max 13 int places and max 2 decimal places. In addition the decimal number uses a comma instead of dot.
I tried some regex but they don't works on keypress.
111111,11 TRUE
1111111111111 TRUE
11111111111111 FALSE
11111111111111,11 FALSE
1111111111111,11 TRUE
111,111 FALSE
1a FALSE
1.0 FALSE
1.00 FALSE
0 TRUE
I tried the following regular expression, and tested it on regextester website. In that site it partially works (some cases still not working), but on javascript it doesn't filter. I don't know the reason.
/^(\d{1,13})(\,)?(\d{1,2})$/g
This is the jquery method
$(".numericWithDecimal").on("keypress keyup blur",function (event) {
var regex = /^(\d{1,13})(\,)?(\d{1,2})$/g;
//I tried this
if(!regex.match($(this).val()))
event.preventDefault();
//or this
if (!regex.test($(this).val()))
event.preventDefault();
});
Is possible to create an expression that works with these cases? What is?
[EDIT] New method based on @The fourth bird regex
$(".numericWithDecimalLimit").on("keypress keyup blur",function (event) {
var regex = /^(?:\d{1,13})(?:,\d{1,2})?$/g;
var value = this.value + String.fromCharCode(event.keyCode || event.charCode);
if(!regex.test(value))
event.preventDefault();
});
Upvotes: 3
Views: 1713
Reputation: 361
after making a small update in your original regex to include dots, seems to be working as expected for me.. I got this in the end /^(\d{1,13})(,|\.)?(\d{1,2})$/g
here are a few test cases:
var regex = /^(\d{1,13})(,|\.)?(\d{1,2})$/g;
console.log(regex.test('111111.11'));
console.log(regex.test('1111111111111'));
console.log(regex.test('11111111111111'));
console.log(regex.test('11111111111111,11'));
console.log(regex.test('1111111111111,11'));
console.log(regex.test('111,111'));
console.log(regex.test('1a'));
console.log(regex.test('1.0'));
console.log(regex.test('1.00'));
console.log(regex.test('0'));
Upvotes: 0
Reputation: 163632
You could update your regex to and include the comma into a non capturing group and make it optional:
That would match:
^
Beginning of the string(\d{1,13})
Capture 1 - 13 digits in a group(?:
Non capturing group
,
Match a comma\d{1,2}
Match 1 or 2 digits)?
Close non capturing group and make it optional$
End of the stringFor the match you could also make the first group a non capturing group:
Upvotes: 1