PHP Form Validation
Form validation ensures data is correct, complete, and safe before processing. Never trust user input - always validate and sanitize!
Output
Click Run to execute your code
Common Validations
| Validation | Function |
|---|---|
| Required field | !empty(trim($value)) |
filter_var($email, FILTER_VALIDATE_EMAIL) |
|
| Length | strlen($value) >= $min && <= $max |
| Numeric | is_numeric($value) |
| URL | filter_var($url, FILTER_VALIDATE_URL) |
Validate Email
<?php
function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
if (validateEmail("[email protected]")) {
echo "Valid email";
}
?>
Sanitize Input
<?php
// Prevent XSS attacks
$name = htmlspecialchars($_POST['name']);
// Remove HTML tags
$text = strip_tags($_POST['text']);
// Sanitize email
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
?>
Summary
- Always validate: Never trust user input
- filter_var(): Built-in validation
- htmlspecialchars(): Prevent XSS
- Collect errors: Show all issues at once
What's Next?
Next, learn about Sessions - maintaining user state across pages!
Enjoying these tutorials?