Validation of javascript fields?

Asked

Viewed 286 times

0

How could you validate a field using document.getElementById and when clicking the button for example "send" appears an alert stating?

2 answers

0

With pure javascript create a function and call it on onsubmit() as argument is passed the form with all its fields, then it is possible to validate them in this way form.campo.value

<html>
<head>
<script>
function validar(form){
    if(!form.nome.value){
        alert('informe o nome');
    }else{
        form.submit();  
    }

}
</script>
</head>
<body>
   <form action="" method="post" onsubmit="validar(this);return false;">
      <input type="text" id="nome" name="nome"/>
      <input type="submit" />
   </form>
</body>
</html>

0

You need to use Event.preventDefault() to stop data submission.

<script>

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

form.addEventListener("submit", function(event){
    var nome = document.getElementById("nome").value;

    if(nome == ""){
        event.preventDefault();
        alert("Por favor preencha o nome");
        return false;
    }

});

</script>
<body>

<form name="teste" id="formulario">
<input type="text" name="nome" id="nome"  />
<input type="submit" value="Enviar">
</form>
</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.