[英]phone number validator js
How Can i allow the function to modify and print the number only if it is of the following format: +XX-XXXX-XXXX?我如何允许 function 修改和打印只有以下格式的号码:+XX-XXXX-XXXX? This is the code that allows invalid phone numbers like simple text
这是允许无效电话号码(如简单文本)的代码
function updatePhone() {
var phoneNumbers = "";
var additionalPhoneNumber = $('#phoneInputAdditional').val() + ",";
$('.phoneInput').each(function () {
if ($(this).val() != "")
phoneNumbers = phoneNumbers + $(this).val().toString() + ",";
console.log($(this).val());
});
if (additionalPhoneNumber != ",")
phoneNumbers = phoneNumbers + additionalPhoneNumber;
phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length - 1);
$.ajax({
type: "POST",
url: "/updatePhone",
data: {"phoneNumbers": phoneNumbers},
dataType: "json"
})
.done(function (response) {
$("#userPhone").text('Phone: ' + response[0]);
$("#phoneul").empty();
for (var i = 1; i < response.length; i++)
$("#phoneul").append('<li class = "col-sm-4 phoneli"> <b>Update Number:</b> <input type = "text" value ="' + response[i] + '" class= "form-control phoneInput"/></li>')
$("#phoneul").append('<li class="col-sm-4"><b>Additional Number:</b> <input type = "text" placeholder = "Another Phone Number" class="form-control" id= "phoneInputAdditional"/></li>')
$("#good3").show();
setTimeout(function(){ $("#good3").hide(); }, 800);
})
.fail(function () {
$("#bad3").show();
});
}
I thought of sth like this:我是这样想的:
if ( $(this).val().test(/^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/) )
phoneNumbers = phoneNumbers + $(this).val().toString() + ",";
console.log($(this).val());
You can check out theRegex Library of regex101 .您可以查看regex101 的正则表达式库。 There you can find a lot of phone number validators.
在那里你可以找到很多电话号码验证器。 The one with the most upvotes is for phone and fax numbers for all over the world and was created by Aditya Joshi .
投票最多的是世界各地的电话和传真号码,由Aditya Joshi创建。 It can be found here: https://regex101.com/r/wZ4uU6/1 , including an example and a debugger.
它可以在这里找到: https://regex101.com/r/wZ4uU6/1 ,包括一个示例和一个调试器。 It is the following:
如下:
\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}
The corresponding example:对应的例子:
const regex = /\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}/g; // Alternative syntax using RegExp constructor // const regex = new RegExp('\\+?\\d{1,4}?[-.\\s]?\\(?\\d{1,3}?\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}', 'g') const str = `+49 172 7470791 +49 621 60-6641516 +49 621 60-41516 8-1-6641516 61 41516 6641516 41516 `; let m; while ((m = regex.exec(str)).== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex;lastIndex++. } // The result can be accessed through the `m`-variable. m,forEach((match. groupIndex) => { console,log(`Found match: group ${groupIndex}; ${match}`); }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.