Validate an HTML form with JAVASCRIPT

1

What would be a way to validate the text field as soon as the button is clicked?

Using only JavaScript .

Ex :

  

If the field is not filled in , and the user clicks the button, it issues an alert and would not let the form be sent and would show which field is blank and missing the fill. p>

<form>
  <fieldset>
    <legend>Teste</legend>
    Informe seu nome: <input tpye="text" size="10">
    <p>
    <input type="submit" value="Validar">
  </fieldset>
</form>
    
asked by anonymous 04.12.2017 / 17:22

3 answers

3

Simple verification using only JavaScript:

var formulario = document.querySelector('form');

formulario.onsubmit = function(){
   if(!document.querySelector("input[type='text']").value){
      alert("Campo nome vazio!");
      return false;
   }
   
   alert("ok");
}
<form>
   <fieldset><legend>Teste</legend>
   Informe seu nome: <input type="text" size="10">
   <input type="submit" value="Validar">
   </fieldset>
</form>

Suggestion

It would be interesting to assign ids to elements such as <form id="formulario"> , or class in fields if there are more fields in the future. This makes it easier to manipulate elements and develop code.

    
04.12.2017 / 17:38
1

As you requested in JavaScript and with alert , then there you go. First you need to give name to your input and its form , and you can do this in this way as I'll show below.

    function validar() {
    
    var nome = formulario.nome.value;
 
      if (nome == "") {
        alert('Preencha o campo com seu nome');
          formulario.nome.focus();
          return false;
       }
    }
    <form name="formulario" action="enviar.php" method="post">
        <fieldset><legend>Teste</legend>
        Informe seu nome: <input  type="text" name='nome'>
        <p>
        <input type="submit" onclick="return validar()">
      </fieldset>
    </form>

Or simply with HTML, you can do this

    <form>
      <fieldset><legend>Teste</legend>
        Informe seu nome: <input  type="text" required>
        <p>
        <input type="submit">
      </fieldset>
    </form>
    
04.12.2017 / 17:28
0

You can use required

It's not pop up like you asked, but it's very useful for a basic form.

<form>
<fieldset><legend>Teste</legend>
Informe seu nome: <input required tpye="text" size="10">
<p>
<input type="submit" value="Validar">
</fieldset>
</form>
    
04.12.2017 / 17:26