Validation of javascript fields?

1

How could I validate a field using document.getElementById and when clicking on the button, for example "send", does an alert inform?

    
asked by anonymous 12.02.2016 / 14:34

2 answers

0

With pure javascript create a function and call it in onsubmit() as argument is passed form with all its fields, so you can 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>
    
12.02.2016 / 14:40
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>
    
12.02.2016 / 15:01