逗号分隔数字列表的掩码

时间:2015-02-18 22:08:36

标签: javascript jquery

我正在为我的输入创建一个逗号分隔值的掩码,但我有困难。

你们能帮助我吗?

这是我当前的面具:

<script>
    $(document).on("keyup keydown keypress", "commaseparated", function (e) {
        if (!$(this).val().match(/^([0-9]{0,1})(,[0-9]{1,}){1,}?$/g)) {
            e.preventDefault();
        }
    });
</script>
<input type="text" class="commaseparated" />
<!-- example input would be
     1235 <- single number
     or
     2654,524874,5456 <- many numbers
-->

提前致谢:)

修改 嗯,这不是一个面具。我想要的是用户只能插入数字和逗号,例如:

123 -> allowed
123,123 -> allowed
123,, -> not allowed
123,letters -> not allowed

2 个答案:

答案 0 :(得分:5)

您可以使用RegExp /(,|\D)(?=\1)|^[,\D]|[^,\d]$/g来匹配逗号或非数字字符,后跟逗号或非数字字符或字符串开头的逗号或非数字或字符串的最后一个字符不是数字或逗号,用空字符串替换匹配。

$(".commaseparated").on("input", function(e) {
  $(e.target).prop("value", function(_, val) {
    return val.replace(/(,|\D)(?=\1)|^[,\D]|[^,\d]$/g, "");
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="commaseparated"/>

答案 1 :(得分:2)

请试试下面的jquery。

//We need to capture the keypress event, as this is triggered before the value is displayed in the text box.
$(document).on("keypress", ".commaseparated", function (e) {
    var currentValue = $(this).val();
    //If the value is empty, let user enter numerals.
    if(currentValue == "" && e.keyCode >= 48 && e.keyCode <= 57) {
        return true;
    }
    else {
        //If some value is there, get the last character.
        var lastChar = currentValue.substr(currentValue.length - 1);

        //If the last character is comma, let user enter numerals.
        if(lastChar == "," && e.keyCode >= 48 && e.keyCode <= 57){
            return true;
        }
        //If the last character is comma, deny entering comma again. 
        else if(lastChar == "," && e.keyCode == 44){
            return false;
        }
        //If the control reaches here and as last character could only be numeral, let user enter only comma or numerals. 
        else if (e.keyCode == 44 || (e.keyCode >= 48 && e.keyCode <= 57)) {
            return true;
        }
        // for everything else, return false. 
        else{
            return false;
        }
    }
});

找到jsfiddle here