使用正则表达式限制文本框中的输入 [英] Using regex to restrict input in textbox
问题描述
/^+{0,1}(?:\d\s?){11,13}$/这个正则表达式只允许 + 放在第一位,并且只允许数字......
/^+{0,1}(?:\d\s?){11,13}$/ this regex allows + at first place only and numbers only...
在按键时,我希望用户首先只能输入 + 和上面正则表达式验证的数字但是代码总是转到 if part..为什么正则表达式在这种情况下不起作用
on keypress I want user should only be able to type + at first and digits that what above regex validates But code always goes to if part..why regex not working in this scenario
function ValidatePhone(phone) {
var expr = /^\+?(?:\d\s?){11,13}$/;
return expr.test(phone);
}
var countofPlus = 0;
$("#phone").on("keypress", function (evt) {
if (evt.key == "+")
{
countofPlus = countofPlus + 1;
if (countofPlus > 1 || this.value.length >= 1) {
return false;
}
else return true;
}
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && charCode != 43 && charCode != 32 && charCode != 40 && charCode != 41 && (charCode < 48 || charCode > 57))
return false;
return true;
});
$("#phone").on("keyup", function (evt) {
debugger;
if (evt.key == "+") {
countofPlus--;
return true;
}
});
推荐答案
改编来自 HTML 输入只需要数字和 + 符号 到您的用例产生以下(IE-)兼容代码:
Adapting an answer from HTML input that takes only numbers and the + symbol to your use-case yields the following (IE-)compatible code:
// Apply filter to all inputs with data-filter:
var inputs = document.querySelectorAll('input[data-filter]');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
var state = {
value: input.value,
start: input.selectionStart,
end: input.selectionEnd,
pattern: RegExp('^' + input.dataset.filter + '$')
};
input.addEventListener('input', function(event) {
if (state.pattern.test(input.value)) {
state.value = input.value;
} else {
input.value = state.value;
input.setSelectionRange(state.start, state.end);
}
});
input.addEventListener('keydown', function(event) {
state.start = input.selectionStart;
state.end = input.selectionEnd;
});
}
<input id='tel' type='tel' data-filter='\+?\d{0,13}' placeholder='phone number'>
以上代码需要复制&粘贴、选择、退格等,以考虑当前实施失败的地方.
Above code takes copy & pasting, selecting, backspacing etc. into account where your current implementation fails.
此外,我将给定的正则表达式修改为 \+?\d{0,13}
以便它允许不完整的输入.使用 HTML5 表单验证来验证最终结果.
Also, I modified the given regex to \+?\d{0,13}
so it allows for incomplete input. Use HTML5 form validation to validate the final result.
这篇关于使用正则表达式限制文本框中的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!