Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

"form must not contain other form elements." so you don't have to use two <form> tags.

Just give your form an ID, and in JavaScript handle the submit event.

<form
   id="myForm"
   action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"
   method="POST"
   >
   <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>
   <button type="submit">Submit</button>
</form>

The script may look like this:

var form = document.getElementById("myForm");

form.addEventListener("submit", function (e) {
  e.preventDefault();

  var target = e.target;
  var formData = new FormData(target);
  var data = Object.fromEntries(formData.entries());

  var regex = /^[0-9]+$/;
  if (
    !data.W_ID.match(regex) ||
    !data.D_ID.match(regex) ||
    !data.C_ID.match(regex)
  ) {
    alert("Only numbers accepted.");
  } else {
    // Continue form submittion.
    this.submit();
  }
});

https://codesandbox.io/s/keen-galileo-tvznl?file=/script.js:0-439

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda