简体   繁体   中英

Javascript to validate URL

I have a text box where the user will enter a URL, and I need to validate this 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.

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

   <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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