Open In App

How to Validate Form Data in PHP?

To validate form data in PHP, we can utilize a combination of sanitization and validation techniques. By accessing form input through PHP’s superglobal arrays like $_POST or $_GET‘, we can sanitize the data using functions like filter_var( ) to remove malicious characters. Subsequently, we validate the input against specific formats or constraints, ensuring accuracy and security in web applications.

Approach:

$name = $_POST["name"];
$email = $_POST["email"];
$gender = $_POST["gender"];
$mobileNumber = $_POST["mobile"];

// Sanitize and validate name
$sanitized_name = filter_var($name, FILTER_SANITIZE_STRING);
if (!preg_match("/^[a-zA-Z\s]+$/", $sanitized_name)) {
// Invalid name
}

// Sanitize and validate email
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)) {
// Invalid email
}

// Validate gender
if (!isset($gender)) {
// Gender not selected
}

// Validate mobile number
if (!preg_match("/^\d{10}$/", $mobileNumber)) {
// Invalid mobile number
}
Article Tags :