6

我正在尝试regular expression使用下面的代码验证 jQuery 中的 URL。它与http://www和一起工作正常https://www

var myVariable = "http://www.example.com/2013/05/test-page-url-512-518.html";

if(/^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/|www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
    alert("valid url");
} else {
    alert("invalid url");
}

编辑:-

上面的代码可以完美地验证 URL。那时我的要求只是验证http://wwwhttps://www

4

5 回答 5

10

检查这个 - http://docs.jquery.com/Plugins/Validation/Methods/url

$("#myform").validate({
  rules: {
    field: {
      required: true,
      url: true
    }
  }
});
于 2013-05-14T07:45:13.897 回答
2

你可以改变你的正则表达式,实际上有一个重复的项目,即http:\/\/|https:\/\/|www\.

此代码将为您解决:

var myVariable = "http://www.example.com/2013/05/test-page-url-512-518.html";

if(/^(http:\/\/www\.|https:\/\/www\.)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(myVariable)){
    alert("valid url");
} else {
    alert("invalid url");
}
于 2013-05-14T07:52:20.103 回答
2

您想验证您的 URL:

请在此函数中传递 URL,然后这将为您提供真或假。

功能 :

<script>
function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

isUrl(yourURL);
</script>
于 2013-09-12T09:21:51.413 回答
1

您的模式定义为

^(http:\/\/|someting else

因此任何以“http://”开头的 URL 都会被验证。

于 2013-05-14T07:47:42.497 回答
0

试试这个--->

var myVariable = "http://www.Test.com/";
if(/^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,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A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(myVariable)) {
  alert("valid url");
} else {
  alert("invalid url");
}
于 2013-05-14T07:45:12.833 回答