Regular expression for URL validation

Some times we may need to validate the URL from back-end or front-end.

I used following codes and works good for me. You can check it once if you need.

So for PHP

    function is_valid_url($url) {
        return preg_match('/^((ht|f)tp(s?)(:\/\/))?([a-z0-9-]+[.]{1})+[a-z0-9-]+(:[0-9]*)?(\/{1}[a-zA-Z0-9\-\.\?\,\:\!\'\/\\\+&%\$#_=]+)*\/?$/i', $url);
    }

And for JS

    function is_valid_url(url) {
        var urlregex = new RegExp(/^((ht|f)tp(s?)(:\/\/))?([a-z0-9-]+[.]{1})+[a-z0-9-]+(:[0-9]*)?(\/{1}[a-zA-Z0-9\-\.\?\,\:\!\'\/\\\+&%\$#_=]+)*\/?$/i);
        return urlregex.test(url);
    }

This will allow following pattern of URL
http://www.abc.com
http://www.abc.com:8080
http://www.abc.com:8080/abc.xyz?a=2&b:c#!landingpage
https://www.abc.com
http://www.abc.com
http://www.abc.com/path/
http://www.yahoo.com/path/to

Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s