How could I validate a field using document.getElementById
and when clicking on the button, for example "send", does an alert inform?
How could I validate a field using document.getElementById
and when clicking on the button, for example "send", does an alert inform?
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>
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>