Skip to content
PHP Logo

How can a Validator class in PHP be utilized to improve form data validation and prevent empty submissions?

Using a Validator class in PHP can improve form data validation by centralizing the validation logic and making it reusable across multiple forms. This can help prevent empty submissions by checking for required fields and ensuring that the data submitted meets certain criteria before processing it further.

php
<?php

class Validator {
    public static function validateForm($formData) {
        $errors = [];

        // Check for required fields
        if (empty($formData['name'])) {
            $errors['name'] = 'Name is required';
        }

        if (empty($formData['email'])) {
            $errors['email'] = 'Email is required';
        }

        // Add more validation rules as needed

        return $errors;
    }
}

// Example form submission
$formData = [
    'name' => $_POST['name'],
    'email' => $_POST['email'],
    // Add more form fields as needed
];

$errors = Validator::validateForm($formData);

if (!empty($errors)) {
    // Display errors to the user
    print_r($errors);
} else {
    // Process the form data
    // e.g. save to database, send email, etc.
}

?>