PHP form > PHP forms tutorial >
Validating URL and E-mail
Validating e-mail, URL and other special types with PHP
On this page we will show a few examples of how to validate e-mails,
website addresses (URLs) and some other special cases of input data.
» Validate e-mail address
There is no way to be 100% sure an e-mail address is actually
working unless you send an e-mail there. What you usually do is
check if the e-mail address syntax is valid. Here is a simple way
to check if data entered into input field named "email"
is an e-mail address without any unnecessary complications and fancy regular
expressions:
$email = htmlspecialchars($_POST['email']);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
die("E-mail address not valid");
}
|
The above code would make the e-mail address required. To make it optional
simply replace
die("E-mail address not valid");
|
with this and the $email variable will simply be empty unless a valid
address is entered:
» Validate URL address
If you have an input field named "website" you can check
for a valid URL address like this:
$url = htmlspecialchars($_POST['website']);
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i",$url))
{
die("URL address not valid");
}
|
Similarly as before to make the URL optional just change:
die("URL address not valid");
|
to this code and $url will be empty if not valid:
» Other special cases
Some other special cases below if you ever need any. You may just
skip it and go to the next page of the tutorial.
Digits 0-9 only
This code will check if $age is a number:
if (preg_match("/\D/",$age))
{
die("Please enter numbers only for Age");
}
|
Letters a-z and A-Z only
This code will check if $text is made of letters a-z and A-Z only (no spaces, digits or any other characters):
if (preg_match("/[^a-zA-Z]/",$text))
{
die("Please enter letters a-z and A-Z only!");
}
|
Anything but whitespace
This code will show an error if $text contains of any whitespace characters (space, tab, newline):
if (preg_match("/\s/",$text))
{
die("Please do not enter any spaces, tabs or new lines!");
}
|
» Copyright notice
© 2008-2024 myPHPform.com. All rights reserved. Copying or redistributing
any part of this website without our written permission is expressly
forbidden!
|