我想限制用户发送包含电子邮件地址或任何 url 的消息。
有什么建议吗?
您应该了解什么是正则表达式 (RegExp),它们对于验证用户输入非常有用!
只是谷歌它
但这里将是您的问题的解决方案:
检查其中是否有电子邮件:
if(input.search(/\b[a-z0-9._%+?\-]+@[a-z0-9.-]+?\.[a-z]{2,4}\b/i) == -1)
{
// Every thing is good
}
else
{
// there is an E-Mail in the input
}
网址有点难,具体取决于您想要的严格程度。
您可能很容易过滤掉实际上不是 url 的东西,但您就可以了。
如果你想非常严格:
if(input.search(/\b[a-z0-9.-]+?\.[a-z]{2,4}\b/i) == -1)
{
// Every thing is good
}
else
{
// there is a url in the input
}
这将过滤任何类似"abc.def.de"
或什至"a.com"
.
如果只有类似"http://asdf.com"
或http://www.dfjdsjfisfi.com
应该过滤的内容,请使用:
if(input.search(/\bhttp:\/\/[a-z0-9.-]+?\.[a-z]{2,4}\b/i) == -1)
{
// Every thing is good
}
else
{
// there is a url in the input
}
input
应该是一个包含消息的字符串,所以在测试之前填写它。
例如var input = $("#input_id").val();
希望有帮助。:)