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

283
Vistas
How to call form validity event if no input is entered

I have a simple form with bootstrap which I need to validate before submitting. It has auto support for invalid-feedback. It looks like this

let forms = document.querySelectorAll(".needs-validation");
var productNameField = document.getElementById("productName");

productNameField.addEventListener("input", function () {
        var val = document.getElementById("productName").value;
        console.log("not entering here if I don't enter an input", val);
        if (!isValidString(val)) {
            productNameField.setCustomValidity("invalid");
        } else {
            productNameField.setCustomValidity("");
        }
    });
    
 
Array.prototype.slice.call(forms).forEach(function (form) {
        form.addEventListener(
            "submit",
            function (event) {
                if (!form.checkValidity()) {
                    console.log("not valid");
                    event.preventDefault();
                    event.stopPropagation();
                }
                console.log("here validation");
                form.classList.add("was-validated");
            },
            false
        );
    });
<form
                    action="/products/addProduct"
                    enctype="multipart/form-data"
                    class="needs-validation"
                    novalidate
                    method="post"
                >
                    <div class="col-md-12 position-relative">
                        <label for="productName" class="form-label"
                            >Product Name</label
                        >
                        <input
                            type="text"
                            name="productName"
                            id="productName"
                            class="form-control"
                        />
                        <div class="invalid-feedback">
                            Please provide a valid Product Name(at least two
                            characters, no special characters allowed).
                        </div>
                    </div>

                    <div>
                        <button type="submit" id="savebutton" name="Submit">
                            Create
                        </button>
                    </div>
                </form>

Now when I type an input I immediately see an error if !validString (because of the input eventlistener). But if I just click on the submit button it is not calling the validString function.

What should I do ?

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

0

    const productNameField = document.getElementById("productName");
    
    const isInputValid = function() {
      return productNameField.value.length > 1;
    }
    const updateValidity = function() {
      if (isInputValid()) {
        productNameField.classList.remove('invalid')
      } else {
        productNameField.classList.add('invalid')
      }
    }
    
    productNameField.addEventListener("input", updateValidity);
    
    
    const forms = document.querySelectorAll(".needs-validation");
    
    Array.prototype.slice.call(forms).forEach(function (form) {
      form.addEventListener(
        "submit",
        function (event) {
          updateValidity();
          if (isInputValid()) {
            console.log("validation complete");
            form.classList.add("was-validated");
          } else {
            console.log("validation failed");
            event.preventDefault();
          }
        }
      );
    });
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