Is it possible to validate input to ensure it contains only digits before submitting a form in PHP?

To validate input to ensure it contains only digits before submitting a form in PHP, you can use regular expressions. You can use the preg_match function to check if the input contains only digits. If the input does not match the pattern of only digits, you can display an error message to the user and prevent the form from being submitted.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $input = $_POST["input_field"];
    
    if (!preg_match("/^[0-9]+$/", $input)) {
        echo "Error: Input must contain only digits.";
    } else {
        // Input is valid, continue with form submission
    }
}
?>