jeudi 4 novembre 2021

Javascript user's input validation on submit

HTML:

      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
        <form name="#" method="POST" onsubmit="return validateForm();">
            <table>
                <tr>
                    <td>Select Warehouse:</td>
                    <td><input type="text" id="W_ID" name="W_ID" placeholder="numbers only"></td>
                    <span class="invalid-feedback"><?php echo $warehouse_err; ?></span>
                </tr>
                <tr>
                    <td>Select District:</td>
                    <td><input type="text" id="D_ID" name="D_ID" placeholder="numbers only"></td>
                    <span class="invalid-feedback"><?php echo $district_err; ?></span>
                </tr>
                <tr>
                    <td>Select Customer:</td>
                    <td><input type="text" id="C_ID" name="C_ID" placeholder="numbers only"></td>
                    <span class="invalid-feedback"><?php echo $customer_err; ?></span>
                </tr>
            </table>

So I tried to validate user's input for W_ID, C_ID and D_ID. For example, if a user input is some strings then return an error message before submitting. I wrote some Javascript code in this .php file but I couldn't get it to work. Please see JS codes below:

Javascript:

        <script>
        function validateForm(){
        var W_ID = document.getElementById("W_ID").value;
        var D_ID = document.getElementById("D_ID").value;
        var C_ID = document.getElementById("C_ID").value;
        var numbers = /^[0-9]+$/;

        //check if input is number
        if(!(W_ID.value.match(numbers) {
            alert('Please only enter numbers.');
        }
        else if(!(D_ID.value.match(numbers) {
            alert('Please only enter numbers.');
        }
        else if(!(C_ID.value.match(numbers) {
            alert('Please only enter numbers.');
        }else {
            alert('Successfully! form has been submitted.');
        }
        </script>

Also how do I wrap JS code inside the PHP? Thank you so much! I've been stuck for long time




Aucun commentaire:

Enregistrer un commentaire