将文本输入限制为由非连续字符分隔的数字组

Restrict text input to number groups separate by a non-consecutive character

本文关键字:字符 连续 分隔 数字 输入 文本      更新时间:2023-09-26

我一直在做很多搜索、裁剪和更改,但我。。。有点迷失了方向,尤其是关于我看到的许多regex示例。

这就是我想做的:

我有一个文本输入字段,大小为32。

我希望用户在其中输入他们的电话号码,但我希望他们至少输入10个数字,用一个逗号分隔。示例:

例如101234567890123456789=右(第一组为>=10个数字,第二组为>=100个数字&组用一个逗号分隔,没有空格或其他符号)

例如20123456789,,0123456789=错误(因为有2个逗号)

例如3012345678901234567890123456789=右侧(与示例1概念相同,但有3组)

我得到了以下内容,但它并没有将逗号限制为每10个数字中有1个,也没有对数字组施加最小字符数。

$(document).ready(function(){
$("#lastname").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != ',' 
&& (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});

最好,我也要提醒用户他们哪里出了问题。例如,如果他们试图输入两个逗号,我想在错误中特别指出,或者如果他们没有插入足够的数字,我想特别在错误中指出。我还想在错误中指出,当既没有插入数字也没有插入逗号时。我想确保选项卡和F5键在键盘上也没有被禁用。非常重要的是,我想特别检测何时使用加号或加号键,并给出不同的错误。我想我是在要求一些有点复杂和不吸引人的东西,所以很抱歉:/

我上面提供的示例代码在所有浏览器中都能很好地工作,但它对我上面提到的任何内容都没有任何最小或最大限制。

如有任何帮助,我们将不胜感激。

作为一个正则表达式,它将检查输入是否有效(1-3个电话号码,由10位数字组成,用逗号分隔),您可以这样做:

^'d{10}(,'d{10}){0,2}$

像下面这样尝试不使用Regex 的代码段

var errrorMessage = '';
function validateLength (no) {
    if(!no.length == 10) {
       return false;
    }
    return true;
}
function validatePhoneNumbers (currentString, splitBy) {
    if(currentString) {
        var isValid = true,
            currentList = currentString.split(splitBy);
        // If there is only one email / some other separated strings, Trim and Return.
        if(currentList.length == 1) {
            errrorMessage = 'Invalid Length in Item: 1';
            if(validateLength( currentString.trim() )) isValid = false;
        }
        else if(currentList.length > 1) {
            // Iterating mainly to trim and validate.
            for (var i = 0; i < currentList.length; i++) {
                var listItem = currentList[i].trim();
                if( validateLength(listItem ) ) {
                   isValid = false;
                   errrorMessage = 'Invalid Length in Item:' + i
                   break;
                }
                // else if for some other validation.
            }
        }
    }
    return isValid;
}
validatePhoneNumbers( $("#lastname").val() );