How can PHP be used to validate form input fields for a contact form?
To validate form input fields for a contact form in PHP, you can use conditional statements and regular expressions to check if the input meets certain criteria such as being a valid email address or not empty. You can also sanitize the input to prevent any malicious code from being executed.
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name field
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
// Validate email field
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// Check if email address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// Additional validation for other fields can be added here
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}