How can server-side validation be implemented effectively when generating dynamic HTML code?

When generating dynamic HTML code, server-side validation can be implemented effectively by validating user input on the server before outputting it to the HTML. This ensures that any malicious or incorrect data is caught before it reaches the client-side. One way to achieve this is by using PHP to validate input data and only displaying it in the HTML if it passes the validation checks.

<?php
// Example of server-side validation in PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $input = $_POST["input_field"];

    // Validate input
    if (/* validation condition */) {
        // Output validated input to HTML
        echo "<p>" . htmlspecialchars($input) . "</p>";
    } else {
        // Handle validation error
        echo "<p>Error: Invalid input</p>";
    }
}
?>