PHP
Form validation basics
Learn to check for empty fields and email format.
Why validate?
Never accept data from the server as is; validate it. The most basic check is catching empty fields with empty(): if (empty($_POST['name'])) { ... }. empty() catches both undefined and empty strings; isset() only catches undefined ones.
To check an email format use filter_var(): if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { ... }. filter_var() is a built-in validation tool; it is safer than writing your own regex.
empty() vs isset()
empty() and isset() check different things. isset($x) returns true if the variable is defined and not null. empty($x) returns true if the variable is undefined, null, "", "0", 0, false or an empty array.
For form validation empty() is handier: if (empty($_POST['name'])) catches both a missing and a blank field in one shot. When the key is missing, empty() does not raise a notice; it treats the undefined variable as false.
Exercise Validate an email
Set $email = "alex@codeblanks.com";. Inside if (filter_var($email, FILTER_VALIDATE_EMAIL)) write echo "Valid";. In the else block write echo "Invalid";.
Show example solution
First write $email = "alex@codeblanks.com";. Then add if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo "Valid"; } else { echo "Invalid"; }.
Example solution:
<?php
// Validate the email
$email = "alex@codeblanks.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid";
} else {
echo "Invalid";
}
Test yourself
-
Match each validation tool to its purpose
- empty()
- Catches empty fields
- isset()
- Checks undefined variable
- filter_var()
- Email format
- htmlspecialchars()
- Stops XSS
-
What is the safest way to check an email format?
- filter_var($email, FILTER_VALIDATE_EMAIL)
- Write your own regex
- Check with strpos($email, '@')
- Check with empty($email)
Show answer
filter_var($email, FILTER_VALIDATE_EMAIL) — Correct. filter_var with FILTER_VALIDATE_EMAIL safely checks the email format.
-
Complete the filter_var email check
if (!____($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid";
}
Show answer
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid";
}
Next lesson: Showing error messages