Page 1 of 1

best way to validate website field

Posted: Fri Jun 25, 2010 7:26 am
by fael097
hi, i have a form with an input to type your website, and i have this pregmatch to validate it:

Code: Select all

preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $validsite)
but turns out that it will only accept results with http:// in front of it, and 99% of people who register their website address wont put http:// .
what would be the best way to validate website?
i need to keep the same format on all registered websites inside my database, cuz they will be a link in user's profile, and i cant have like

Code: Select all

<a href="www.user.com">
or

Code: Select all

<a href="http://http://www.user.com">
any thoughts about that?
thanks in advance!

Re: best way to validate website field

Posted: Fri Jun 25, 2010 12:48 pm
by Jonah Bron
A quick and dirty method.

Code: Select all

$url = str_replace('http://', '', $url);
$url = 'http://' . $url;
// then check with regex

Re: best way to validate website field

Posted: Fri Jun 25, 2010 1:27 pm
by fael097
thats exactly what i was looking for!
thanks mate!

Re: best way to validate website field

Posted: Fri Jun 25, 2010 1:58 pm
by fael097
well, after trying that, i realized that my pregmatch regex is useless. it only restricts the string to something that has http:// in front of it, and since now, it puts http:// automatically, i can type anything on the website field, and it will accept. (almost anything, with a few exceptions) but if i put "asdfasdf" it will accept, you know? it does not require a .com or similar in the end.

i need a better regex, my current one is:

Code: Select all

function validsite($validsite)
	{
		return (preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $validsite));
	}
i got it on google, but i needed one that accepts the following string format:
http:// (letters, numbers, dots, dashes, slashes, etc) dot (letters only, 2 or 3 digits) [like com, co, net, it, tk, i dont know if numbers are needed, i've only seen extensions with 2 or 3 characters, and no numbers, please correct me](and anything again, like whatever can come after the .com, or .co (.uk) or .net/extension.php?adads=asd&asdasd)

idk if im very clear, but i hope so!
thanks again