[英]How do I write a regular expresssion for phone number that allows number only with plus sign?
I am writing a simple validation for a phone number text input.我正在为电话号码文本输入编写一个简单的验证。 I want this text input not to allow any letters and symbols .我希望这个文本输入不允许任何字母和符号。 I only want to allow number and a plus sign at the beginning of the number.我只想在数字的开头允许数字和加号。 The plus sign is optional.加号是可选的。
Current code:当前代码:
$(document).on("input", ".book-appointment-phone", function() {
let phoneRegex = /[^0-9]/g;
var digits = this.value.replace(phoneRegex, '');
return phoneRegex.test(this.value = digits);
});
The current code above can allow numbers only.上面的当前代码只能允许数字。 Do you know how can I update the code above to allow an optional + sign at the beginning of the phone number?您知道如何更新上面的代码以允许在电话号码开头使用可选的+号吗?
For example:例如:
Any help is greatly appreciated.任何帮助是极大的赞赏。 Thank you.谢谢你。
Try this尝试这个
^[\+\d]?(?:[\d-.\s()]*)$
https://regex101.com/r/npGFhU/1 https://regex101.com/r/npGFhU/1
^\+?\d*$
Matches your + at the start, then any digit, dash, space, dot, or brackets匹配开头的 +,然后匹配任何数字、破折号、空格、点或括号
you can check it here: http://regex101.com/r/mS9gD7你可以在这里查看: http : //regex101.com/r/mS9gD7
Try this;尝试这个;
^[\+]?[\d]*$
In the beginning of the expression, + is optional, then variable numbers.在表达式的开头,+ 是可选的,然后是变量数字。
This code might work for you.此代码可能对您有用。
$(document).on("input", ".book-appointment-phone", function() { let phoneRegex = /([^0-9\\+])|(?<!^)(\\+)/g; var digits = this.value.replace(phoneRegex, ''); return phoneRegex.test(this.value = digits); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="book-appointment-phone">
It doesn't make sense to use the same regex for replace
and for test
.对replace
和test
使用相同的正则表达式是没有意义的。 For replace, the regex should be对于替换,正则表达式应该是
/(?!^\+)\D+/g
where \\D
is any non-digit character, and (?!^\\+)
is a negative lookahead that prevents the \\D
matching if it is a +
at the start of the string.其中\\D
是任何非数字字符,并且(?!^\\+)
是一个否定的前瞻,如果它是字符串开头的+
,它会阻止\\D
匹配。
document.querySelector('input').addEventListener('input', function () { let phoneNumber = this.value; // Disallow non-digits. Allow '+' if at start. phoneNumber = phoneNumber.replace(/(?!^\\+)\\D+/g, ''); // Allow, for example, 10 digits maximum. phoneNumber = phoneNumber.replace(/(\\+?\\d{10}).+/, '$1'); this.value = phoneNumber; });
<input type="text">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.