繁体   English   中英

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

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

我一直在进行大量的搜索,修改和更改,但是我...迷路了,尤其是在我所见过的许多正则表达式示例方面。

这就是我想做的:

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

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

例如1 0123456789,0123456789 =右(第一个组> = 10个数字,第二个组=> = 10个数字,并且组用单个逗号分隔,没有空格或其他符号)

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

例如3 0123456789,0123456789,0123456789 =正确(与例如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() );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM