Javascript regex to match only up to 11 digits, one comma, and 2 digits after it

て烟熏妆下的殇ゞ 提交于 2021-01-29 12:10:18

问题


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 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 comma 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 comma must be avoided, so the regex I proposed is not valid since only prevents dots (.).


回答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 this
    var txt = $(this).val() + key;

    if (!pattern.test(txt)) {
        e.preventDefault();
    }
});

jsfiddle example




回答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.



来源:https://stackoverflow.com/questions/13491589/javascript-regex-to-match-only-up-to-11-digits-one-comma-and-2-digits-after-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!