Validate an HTML form with JAVASCRIPT

Asked

Viewed 3,838 times

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 completed, and the user to click the button it emits an alert and would not let the form be sent and would show which field is blank and missing the fill.

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

  • to put the required input in your input, and the field would be validated

  • Puts a idin that <input> and give an Alert for javascript. Check out this link. https://www.w3schools.com/js/js_validation.asp

  • If you found the answer useful, be sure to dial ✔

3 answers

3

Simple verification using Javascript only:

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 the elements, such as <form id="formulario">, or class in the fields if there are more fields in the future. This facilitates the manipulation of the elements and in the development of the code.

1

As you requested in Javascript and with alert then there you go. First you’ll need to give a name for your input and your form, and can do it this way as I will 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>

  • jQuery is a framework, that is, it is the javascript itself redefined in a more modern, simple to use and that uses less code.

  • edited response @LINQ

0

You can use the required

It’s not a pop up like you asked, but it’s quite 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>

Browser other questions tagged

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