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

204
Vistas
Cancelling onSubmit with JS Field Validation

I am trying to validate length of password and display a warning message but message is temporary. I have tried using the onsubmit attribute with the submit button but it still doesn't work.

        function validate()
        {
            var pw = document.getElementById("password").value
            if(pw.length<8)
            {
                document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
            }
        }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <form action="">
            <input type="text" id="password"/>
            <br/>
            <span id="span" style="color:red;"></span>
            <button onclick="validate()">Submit</button>
        </form>
        
    </body>
    </html>

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

0

There were a few things fixed below:

  • Pass the event to your validate(), like this: onclick="validate(event)".
  • Cancel the regular event that happens with onsubmit by means of Event.preventDefault() and return false, but the former is much more important.

Notice what you see below when password is too short and when password is long enough:

        function validate(ev)
        {
            var pw = document.getElementById("password").value
            if(pw.length<8)
            {
                document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>";
                ev.preventDefault();
                return false;
            }
        }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <form action="">
            <input type="text" id="password"/>
            <br/>
            <span id="span" style="color:red;"></span>
            <button onclick="validate(event)">Submit</button>
        </form>
        
    </body>
    </html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

      document.querySelector('form').addEventListener('submit', validate);

        function validate(event) {
            event.preventDefault();

            const form = new FormData(event.target);
            const password = form.get('password').trim();

            if (password.length < 8) {
                document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
                return;
            }

            event.target.submit();
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="">
        <input name="password" type="text" id="password"/>
        <br/>
        <span id="span" style="color:red;"></span>
        <button type="submit">Submit</button>
    </form>
    
</body>
</html>

Your script should look something like this:

       document.querySelector('form').addEventListener('submit', validate);

        function validate(event) {
            event.preventDefault();

            const form = new FormData(event.target);
            const password = form.get('password').trim();

            if (password.length < 8) {
                document.getElementById("span").innerHTML = "Password length must be more than 7 characters.<br/>"
                return;
            }

            event.target.submit();
        }

I put the .trim() because it is usually a good idea to trim the inputs. Consider this if you are using the inline attributes: "You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient. " This is from the mdn documentation -> https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

about 4 years ago · Juan Pablo Isaza Denunciar

0

            var ssn = document.getElementById("ssn");
    var current = document.getElementById("current");
    
    ssn.oninput = function(event) {
      current.textContent = ssn.value;
    }
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
        </head>
        <body>
            <form action="">
                <label for="ssn">password:</label>
        <input type="password" id="ssn" inputmode="numeric" minlength="9" maxlength="12"
            pattern="(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -])?(?!00)\d\d\3(?!0000)\d{4}"
            required autocomplete="off">
        <br>
        <label for="ssn">Value:</label>
        <span id="current"></span>
                <span id="span" style="color:red;"></span>
                <button onclick="validate()">Submit</button>
            </form>
            
        </body>
        </html>

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