Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda