0

我有一个文本框,我只希望最多允许 11 位数字、一个可选的逗号以及后面的两个数字。将键按下文本框时,不应呈现任何其他内容:

$('#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();
  }
});

上面的代码在按下无效键时有效,例如字符或点,但不能确保只有一个逗号和后面的 2 位数字。

这必须匹配:

12314
123123,44

这不得:

12313,6666

是一个演示。

更新:必须避免除数字和逗号之外的任何数字,因此我提出的正则表达式无效,因为只能防止点 (.)。

4

2 回答 2

3

您应该测试您的完整字符串,而不仅仅是当前字母。

$('#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();
    }
});

​</p>

jsfiddle 示例

于 2012-11-21T11:36:57.063 回答
2

regex将匹配任何包含 1 到 11 位数字的字符串,可选地后跟一个,2 位数字:^[0-9]{1,11}(,[0-9]{2})?$

解释:

^             # 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

在这里查看它的实际应用。

于 2012-11-21T10:54:55.720 回答