admin管理员组文章数量:1417070
I have a textbox where I want only allowed up to 11 digits, an optional ma, and two more digits after it. Anything else should not be rendered when the key is pressed into the textbox:
$('#txt').keypress(function (e) {
var code = e.which;
var key = String.fromCharCode(code);
// REGEX TO AVOID CHARS & A DOT (.)
var pattern = /[a-zA-Z]|\./g;
var isMatch = pattern.test(key);
if (isMatch) {
// DO NOT RENDER CHARS & dot
e.preventDefault();
}
});
The above code works when an invalid key is pressed, such as a char or a dot, but does not ensure only one ma and only 2 digits afterwards.
This must match:
12314
123123,44
This must not:
12313,6666
Here is a demo.
UPDATE: Any digit except numbers and ma must be avoided, so the regex I proposed is not valid since only prevents dots (.).
I have a textbox where I want only allowed up to 11 digits, an optional ma, and two more digits after it. Anything else should not be rendered when the key is pressed into the textbox:
$('#txt').keypress(function (e) {
var code = e.which;
var key = String.fromCharCode(code);
// REGEX TO AVOID CHARS & A DOT (.)
var pattern = /[a-zA-Z]|\./g;
var isMatch = pattern.test(key);
if (isMatch) {
// DO NOT RENDER CHARS & dot
e.preventDefault();
}
});
The above code works when an invalid key is pressed, such as a char or a dot, but does not ensure only one ma and only 2 digits afterwards.
This must match:
12314
123123,44
This must not:
12313,6666
Here is a demo.
UPDATE: Any digit except numbers and ma must be avoided, so the regex I proposed is not valid since only prevents dots (.).
Share Improve this question edited Nov 21, 2012 at 11:15 anmarti asked Nov 21, 2012 at 10:48 anmartianmarti 5,14310 gold badges61 silver badges96 bronze badges2 Answers
Reset to default 3You should test your plete 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 this
var txt = $(this).val() + key;
if (!pattern.test(txt)) {
e.preventDefault();
}
});
jsfiddle example
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 ma and 2 more digits
$ # Followed by the end of the string
See it in action here.
本文标签:
版权声明:本文标题:jquery - Javascript regex to match only up to 11 digits, one comma, and 2 digits after it - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745259548a2650291.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论