How can JavaScript be utilized to validate and format user input before submitting it to PHP for further processing?

When submitting user input to PHP for processing, it is important to validate and format the input on the client-side using JavaScript to ensure data integrity and prevent errors. This can be achieved by creating JavaScript functions to check for specific input patterns, such as valid email addresses or required fields, before allowing the form to be submitted to PHP. Once the input is validated and formatted correctly, it can be safely sent to PHP for further processing.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $email = $_POST['email'];

    // Validate and format user input
    $username = filter_var($username, FILTER_SANITIZE_STRING);
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);

    // Further processing of validated input
    // e.g. saving to database or sending email
}
?>