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 Answers
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?:\/\/)?.+/);
2 Comments
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;
}
}