Javascript Regex To Match Only Up To 11 Digits, One Comma, And 2 Digits After It
I have a textbox where I want only allowed up to 11 digits, an optional comma, and two more digits after it. Anything else should not be rendered when the key is pressed into the t
Solution 1:
You should test your complete string, not only the current letter.
$('#txt').keypress(function (e) {
var key = String.fromCharCode(e.which);
var pattern=/^[0-9]{1,11}(,[0-9]{0,2})?$/;
// test thisvar txt = $(this).val() + key;
if (!pattern.test(txt)) {
e.preventDefault();
}
});
Solution 2:
This regex
will match any string containing 1 up to 11 digits optionally followed by a ,
and exactly 2 more digits: ^[0-9]{1,11}(,[0-9]{2})?$
Explanation:
^ # Match the start of the string
[0-9]{1,11} # Followed by a maximum of 11 digits
(,[0-9]{2})? # Optionally followed by a comma and 2 more digits $ # Followed by the end of the string
See it in action here.
Post a Comment for "Javascript Regex To Match Only Up To 11 Digits, One Comma, And 2 Digits After It"