在没有验证插件的情况下使用 jQuery 验证 url?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2723140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating url with jQuery without the validate-plugin?
提问by Martti Laine
I need to validate a url in variablewith jQuery, but can't use validate-plugin. Is there a simple way to do this?
我需要使用 jQuery验证变量中的 url ,但不能使用验证插件。有没有一种简单的方法可以做到这一点?
回答by Nick Craver
You can use the same regex that the validation plugin does (updated to latest regex on May 23rd, 2015):
您可以使用与验证插件相同的正则表达式(2015 年 5 月 23 日更新为最新的正则表达式):
function isUrlValid(url) {
return /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url);
}
var testCases = [
"http://www.google.com/",
"https://www.google.com/",
"ftp://www.google.com/",
"http://google.com/",
"http://google.com",
"https://google.com",
"http://www.google.com:80/",
"https://www.google.com:443/",
"http://127.0.0.1/",
"http://127.0.0.1:9200/",
"www.site.com",
"x:",
"http://",
"javascript:alert('xss')",
"http://w",
"http:",
"derp://www.google.com",
"http://localserver"
], div = document.getElementById("output");
for(var i=0; i < testCases.length; i++) {
var test = testCases[i];
div.innerHTML += (isUrlValid(test) ? "<span class='valid'>valid</span>: " : "<span class='invalid'>invalid</span>: ") + "" + test + "\n";
}
.valid { color: green; }
.invalid { color: red; }
<pre id="output"></pre>
This handles unicode, etc so it's a bit verbose. Source is the validation plugin itself. A few notes: it is probably what you want, but it is not strictly correct. Typically you need to choose a slightly different regex if you want to accept things like http://w
and http://localserver
which are valid in an intranet environment but not typically allowed in most web forms. In a way, this regex is safer because it requires a FQDNin such cases. Similarly other examples like custom protocols are rejected here, but are valid and do work for many things used today. If you're asking users "what's your homepage?" in a form though...you likely want to exclude these anyway.
这处理 unicode 等,所以它有点冗长。源是验证插件本身。一些注意事项:它可能是您想要的,但并不严格正确。通常你需要的,如果你要接受的东西都喜欢选择一个稍微不同的正则表达式http://w
和http://localserver
它们在Intranet环境中有效,但通常不能在大多数网页表单。在某种程度上,这个正则表达式更安全,因为在这种情况下它需要FQDN。类似地,其他示例(如自定义协议)在此处被拒绝,但它们是有效的并且适用于当今使用的许多事物。如果你问用户“你的主页是什么?” 虽然以某种形式......无论如何你可能想排除这些。
Anyone finding this later: please feel free to test additional test cases with the snippet I included and update the answer if you feel a new common case should be mentioned. I re-wrote the answer with the latest regex and in this format to better serve the community.
稍后发现此问题的任何人:请随时使用我包含的代码段测试其他测试用例,如果您觉得应该提及一个新的常见用例,请更新答案。我用最新的正则表达式和这种格式重新编写了答案,以更好地为社区服务。
回答by Ersin Demirtas
Thank you very much Meo and Nick, I put both your answers together and it works just great.
非常感谢 Meo 和 Nick,我把你的答案放在一起,效果很好。
if(/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test($("#url").val())){
alert("valid URL");
} else {
alert("invalid URL");
}
回答by James Moberg
If you are sure that your audience is using HTML5, you can use type="url"
to validate the text string. You could also dynamically create an input element, set the type and test whether the variable is valid URL or not.
如果您确定您的受众正在使用 HTML5,则可以使用type="url"
来验证文本字符串。您还可以动态创建一个 input 元素,设置类型并测试该变量是否为有效的 URL。
The following is based on a blog post from https://www.raymondcamden.com/2016/10/19/using-html-form-validation-in-pure-javascript
以下内容基于https://www.raymondcamden.com/2016/10/19/using-html-form-validation-in-pure-javascript的博客文章
var elm;
function isValidURL(u){
if(!elm){
elm = document.createElement('input');
elm.setAttribute('type', 'url');
}
elm.value = u;
return elm.validity.valid;
}
console.log(isValidURL('http://www.google.com/'));
console.log(isValidURL('//google.com'));
console.log(isValidURL('google.com'));
回答by Abdo-Host
var url = $('input.surl').val();
url_validate = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
if(!url_validate.test(url)){
alert('error');
}
else{
alert('success');
}
回答by meo
yes with a regex:
是的,使用正则表达式:
/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix
回答by Vishnu Sharma
you Want to validate your URL:
Please pass the URL in this function then this will give you trueOR false.
See Function :
您想验证您的网址:
请在此函数中传递 URL,然后这将为您提供true或false。
见功能:
<script>
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
isUrl(yourURL);
</script>
回答by Akash Mane
Code :
代码 :
var re = /^(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/;
re.test('http://www.goole.in');