hi friends, I just want to validate url,for both folowing formats http://www.XYZ.com and www.XYZ.com i want this validation script in Javascript and PHP also. Thanks in advance.
+3
A:
Regex like a champ.
You could write one yourself, here's a quick example:
(https?://)?.+$
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: http://www.geekzilla.co.uk/view2D3B0109-C1B2-4B4E-BFFD-E8088CBC85FD.htm (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 = "http://www.XYZ.com";
var isValidURL = urlString.match(/(https?:\/\/)?.+/);
Ben
2009-06-16 09:26:02
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 (http://us2.php.net/manual/en/function.gethostbyname.php) 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:34
the above condition will validate for both below condition? www.xyz.com and http://www.xyz.com
Avinash
2009-06-16 09:47:06
what about testing it yourself? http://squarefree.com/shell/shell.html
Alsciende
2009-06-16 10:05:28
+2
A:
You'd be best using a regular expression to do this. Something like this:
^((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+)*)?
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+)*)?';
if(url.match(pattern))
{
return true;
}
else
{
return false;
}
}
Kieran Hall
2009-06-16 09:26:51
the above condition will validate for both below condition?www.xyz.comand http://www.xyz.com
Avinash
2009-06-16 09:42:28
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:24