简体   繁体   English

验证网址的Javascript

[英]Javascript to validate URL

I have a text box where the user will enter a URL, and I need to validate this URL. 我有一个文本框,用户将在其中输入URL,并且需要验证此URL。

For example: I'm only trying to validate this part: 例如:我只是想验证这一部分:

(https/http/ftp://www.gmail.two letters here)

I mentioned two letters there because many TLDs exist such as .cc, .me, etc. 我之所以提到两个字母是因为存在许多顶级域名,例如.cc,.me等。

I tried this regex which did not work: 我尝试了这个不起作用的正则表达式:

(/((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/)

Correct me if I'm wrong. 如果我错了纠正我。

Could just simply use: 可以简单地使用:

((https?|ftp):\/\/)+([\w\d\.]+([\w]{2,6})?)

Depending on what your need is, you can go with simplicity or with... overkill. 根据您的需求,您可以选择简单或过度使用。 :p :p

   <html>
        <div>
            <ul>
                <li>http://www.stackoverflow.com</li>
                <li>httpwww.stackoverflow.com</li>
                <li>a.b.c</li>
            </ul>
        </div>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript">
        function IsURL(str_url){  

        var strRegex = "[a-zA-z]+://[^\s]*";  
              var re=new RegExp(strRegex);  
              if (re.test(str_url)){  
                  return (true);  
              }else{  
                  return (false);  
              }  
          }  
    $(document).ready(function(){  
        $("li").click(function(){  
            var url=$(this).text();  
                alert(url+" /n IsURL:"+IsURL(url));  
            });  
        });  
    </script>
    </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM