What are some best practices for handling form validation on dynamically assembled webpages in PHP?

When handling form validation on dynamically assembled webpages in PHP, it is important to ensure that the validation logic is applied consistently across all dynamically generated forms. One effective way to achieve this is by using a centralized validation function that can be called for each form submission. This function should validate the form fields based on predefined rules and return any errors that need to be displayed to the user.

<?php

function validateForm($formData) {
    $errors = [];

    // Validate form fields based on predefined rules
    if(empty($formData['name'])) {
        $errors['name'] = 'Name is required';
    }

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

    // Add more validation rules as needed

    return $errors;
}

// Example usage
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $formErrors = validateForm($_POST);

    if(empty($formErrors)) {
        // Form is valid, process the data
    } else {
        // Display errors to the user
        foreach($formErrors as $error) {
            echo $error . '<br>';
        }
    }
}

?>