Skip to content
PHP Logo

What are the advantages of using a Validator class in PHP, and how can it help streamline form validation processes?

Using a Validator class in PHP can help streamline form validation processes by centralizing validation rules, making it easier to maintain and reuse code. It can also improve code readability and organization by separating validation logic from other parts of the application.

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

        // Validation rules
        if (empty($formData['username'])) {
            $errors['username'] = 'Username is required';
        }

        if (empty($formData['email']) || !filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = 'Invalid email address';
        }

        return $errors;
    }
}

// Example of how to use the Validator class
$validator = new Validator();
$formData = $_POST;

$errors = $validator->validateForm($formData);

if (!empty($errors)) {
    // Display errors to the user
    foreach ($errors as $error) {
        echo $error . '<br>';
    }
} else {
    // Process form data
}