【发布时间】:2016-03-17 10:37:13
【问题描述】:
我正在编写电话号码验证。我需要允许用户仅在输入字段的开头写入+ 字符,并防止用户稍后在字段中写入。
换句话说:
+11111111 - 对,
111111111 - 对,
+111+111+ - 假,
1111+111+ - 假
问题是我需要在输入时执行验证。结果我无法在提交后分析整个字符串,因此无法获取+ 字符的位置,因为'keyup' 总是返回0。
我尝试了很多方法,这是其中之一:
$('#signup-form').find('input[name="phone"]').on('keyup', function(e) {
// prevent from typing letters
$(this).val($(this).val().replace(/[^\d.+]/g, ''));
var textVal = $(this).val();
// check if + character occurs
if(textVal === '+'){
// remove + from occurring twice
// check if + character is not the first
if(textVal.indexOf('+') > 0){
var newValRem = textVal.replace(/\+/, '');
$(this).val(newValRem);
}
}
});
当我尝试用空字符串替换 + 字符时,它只被替换一次这是不够的,因为用户可能会错误地输入它多次。
这里是小提琴的链接:https://jsfiddle.net/johannesMt/rghLowxq/6/
请在这种情况下给我任何提示。谢谢!
【问题讨论】:
-
试试
$(this).val($(this).val().replace(/[^\d.+]|(.)\++/g, '$1')); -
@WiktorStribiżew 你的回答是有效的,你可以把它贴在下面,我会接受它。
标签: javascript jquery regex string validation