best way to validate website field

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
fael097
Forum Commoner
Posts: 34
Joined: Sat Mar 06, 2010 7:57 pm

best way to validate website field

Post 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!
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: best way to validate website field

Post by Jonah Bron »

A quick and dirty method.

Code: Select all

$url = str_replace('http://', '', $url);
$url = 'http://' . $url;
// then check with regex
fael097
Forum Commoner
Posts: 34
Joined: Sat Mar 06, 2010 7:57 pm

Re: best way to validate website field

Post by fael097 »

thats exactly what i was looking for!
thanks mate!
fael097
Forum Commoner
Posts: 34
Joined: Sat Mar 06, 2010 7:57 pm

Re: best way to validate website field

Post 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
Post Reply