Validate URL with javascript and php

Go To


I just want to validate url,for both folowing formats and i want this validation script in Javascript and PHP also. Thanks in advance.

2009-06-16 09:02
by Avinash


Regex like a champ.

You could write one yourself, here's a quick example:


A little googling found me something a little more particular, in terms of more strictly validating:

^(https?://)?(([0-9a-z_!'().&=$%-]: )?[0-9a-z_!'().&=$%-]@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!'()-]\.)([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!*'().;?:@&=$,%#-])/?)$

Source: (Obviously test the copied and pasted regex, as you would with any copy pasted code)

If you don't know how to use regexes in PHP, it's as simple as:

$valid = preg_match($pattern, $urlOrStringToValidate);

where $pattern = "/(https?://)?.+/" or something like that, between / and /

Javascript has an object method called match on the String type.

var urlString = "";
var isValidURL = urlString.match(/(https?:\/\/)?.+/);
2009-06-16 09:26
by Ben
Another thing I forgot to mention, regexes will just validate well-formedness of urls. You can actually see if these urls are valid by doing things like sending an AJAX request to the url (Jquery: $.ajax({url: urlToTest, error: function(){ alert("not valid url"); }});

Similarly you can either curl or do a gethostbyname ( to test.

BUT! my experience testing the actual validity of a url has been quite annoying. Say a server takes too long to respond so the ajax fails, or the hostname is an ip address...really a pain to handle - Ben 2009-06-16 09:32

the above condition will validate for both below condition? and - Avinash 2009-06-16 09:47

what about testing it yourself? - Alsciende 2009-06-16 10:05


You'd be best using a regular expression to do this. Something like this:


You can use regular expressions in PHP using the preg_match function and in JavaScript using the match() function.

E.g (Javascript).

function validateUrl(url)
    var pattern = '^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?';

        return true;
        return false;
2009-06-16 09:26
by Kieran Hall
the above condition will validate for both below condition? and - Avinash 2009-06-16 09:42
I belive so. I've not properly tested the expression. You just need to Google around for one that suits your needs and apply that. Either that, or write your own expression that fits your needs exactly - Kieran Hall 2009-06-16 09:59


Use Jquery validator.

2009-06-16 10:21
by Elzo Valugi