Jump to content

best way to validate website field


fael097

Recommended Posts

hi, i have a form with an input to type your website, and i have this pregmatch to validate it:

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

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

or

<a href="http://http://www.user.com">

any thoughts about that?

thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/205840-best-way-to-validate-website-field/
Share on other sites

  $exp = explode(".",$validsite) ;
    if($exp[0]!= "http://www" && $exp[0] != "HTTP://WWW")
{
$correct= "http://$validsite";
preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $correct)
}  else {
preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $validsite)
}

 

It corrects submitted URL.

hey thanks mate, worked really great!

now i just have another question:

 

my regex accepts anything, if it has a http:// in front of it, and since now it puts the http automatically, anything goes. so my regex is useless lol. i wanted to make at least it require a dot something, like it accepts 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 lol.

heres the regex again:

function validsite($validsite)
{
	return (preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $validsite));
}

I always prefer.

 

$url = "http://ww.testychicken.co.uk";
$url = explode("?",$url) ;
if (preg_match("/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i", $url[0])) {
echo "Valid URL";
}
else {
echo "Invalid URL";
}

 

It works like this, Either  http or ftp is accepted. followed by alpha numeric characters. allows sub-domains also it accepts endings of at least 2 digit long . tk, in, ca or others like co.in , co.uk, co.us etc etc.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.