老实说,这听起来像一个重复的帖子,但这是完全不同的其他帖子。
我正在构建一个聊天室,在这里我想检测用户发送消息的移动号码,并警告用户在聊天室发送移动号码是不安全的,这违反了我们的政策。
很少有帖子显示如何检测美国号码。但是印度的数字呢?它们是10位数。
var input = "hey im emily, call me now 9876543210"我必须检测所有这些格式的数字。
9876543210
9 8 7 6 5 3 2 1 0
98765 43210
+919876543210
+91 9876543210
一些智能用户总是想出一种聪明的方法来绕过客户端javascript中使用的过滤器。所以我必须做好充分的准备来检测他们使用的所有方法。
示例消息:
“嘿这是我现在打电话给我9876543210”
预期输出:弹出时说,嘿,伙计,在房间里发送号码是不安全的,这里不允许。
注意:应该允许字符串消息发送upoto 5位数字,而不需要弹出警报。或者你有什么更好的主意?建议我,我们就能让它发挥作用。谢谢
发布于 2019-10-15 13:19:33
在测试用例中,电话号码的长度是10。
因此,尝试以下代码:
let input = "hey im emily, call me now 9 876543210";
let matched = input.match(/\d+/g).join('');
let phoneNumberLength = 10;
if (matched.length >= phoneNumberLength) {
console.log(`we've found a phone number. The number is ${matched}`);
} else
console.log(`The message does not contain phone number`);
尝试根据需要调整这段代码
更新:
这段代码旨在通过@tibetty获得测试用例所需的结果:
let input = 'hi dude, please call my cell phone +86 13601108486 at 300pm"'
let matched = input.split(' ');
let maxIndex = matched.length - 1;
let filtered = matched.filter((s, i) => {
if (i != maxIndex && isNumeric(s) && isNumeric(matched[i + 1]))
return true;
if (isNumeric(s))
return true;
return false;
});
console.log(` The number is found ${filtered.join(' ')}`);
function isNumeric(n) {
return n.match(/^(?:[+\d].*\d|\d)$/);
}
发布于 2019-10-15 13:16:04
这里是一个7或10位数字的正则表达式,允许扩展,分隔符是空格、破折号或句点:
^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
虽然您需要为诸如911、100、101这样的特殊号码添加条件
发布于 2019-10-15 13:11:32
试试这个:https://www.w3resource.com/javascript/form/phone-no-validation.php
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}https://stackoverflow.com/questions/58395506
复制相似问题