Regex Form Validation
Use regex to validate form inputs in PHP. Combine with PHP's filter functions for comprehensive validation.
Use regex to validate form inputs in PHP. Combine with PHP's filter functions for comprehensive validation.
<?php
function validateForm(array $data): array {
$errors = [];
// Email
if (!filter_var($data["email"], FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Invalid email";
}
// Phone (US format)
if (!preg_match("/^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/", $data["phone"])) {
$errors["phone"] = "Invalid phone number";
}
// Password strength
if (!preg_match("/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/", $data["password"])) {
$errors["password"] = "Password must be 8+ chars with upper, lower, and digit";
}
return $errors;
}
Use PHP's filter_var() for email/URL/IP validation — it is more accurate than most hand-crafted regex.