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:
- Accessing Form Data: Retrieve form input using PHP’s
$_POST
superglobal array. - Sanitizing Name and Email: Use
filter_var()
withFILTER_SANITIZE_STRING
to remove unwanted characters from the name. Sanitize the email usingfilter_var()
withFILTER_SANITIZE_EMAIL
. - Validating Name and Email: Check if the name contains only letters and whitespace using a regular expression. Validate the email format using
FILTER_VALIDATE_EMAIL
. - Validating Gender: Ensure that the gender is selected by checking if it’s set using
isset()
. - Validating Mobile Number: Use a regular expression (
\d{10}
) to validate the mobile number, ensuring it has 10 digits. - Error Handling: Display error messages if any validation fails, guiding users on correct input formats.
- Improving Usability: Enhance the user experience by providing clear and informative error messages for each validation failure.
- Validation: Validate each input according to the specified rules:
- Name: Make the field as required. It must contain only letters and whitespace.
- E-mail: Make the field as required, It must contain a valid email address.
- Gender: Make the field as required, It must select one option.
- Mobile Number: Make the field as required, It must contain a valid mobile number format (e.g., 10 digits).
$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
}