Validation form

-2

Create the CSS style class named "invalid", whose formatting is as follows: # A00 and white text. Change form validation so that if a form field is invalid, assume this class. If it is correct, go back to the default style

<div>
  <label for="txtNome">Nome:</label>
</div>
<div>
  <input type="text" id="txtNome" name="txtNome" size="50" maxlength="100">
  <p class="aviso" id="avisoTxtNome" style="display:none;">Este campo não pode ficar vazio!</p>
</div>

if (document.getElementById("txtNome").value.length < 3) {
  alert('Por favor, preencha o campo nome');
  document.getElementById("txtNome").focus();
  return false
}

That is, change the alert to what is in html, but using these methods.

    
asked by anonymous 14.02.2016 / 15:52

1 answer

0

Change the event ( onkeyup ) according to your needs ( onblur , onfocus , ...).

Run the code below and start typing letter by letter to understand:

var elementoValidar = document.getElementById('txtNome');

function valida() {
    if (elementoValidar.value.length < 3) {
    	elementoValidar.className = "invalido";  
    } else {
        elementoValidar.className = "ok";  
    }
}
input[type="text"].invalido {
  background-color : #a00; 
  color: #fff;
}

input[type="text"].ok {
  background-color : #0a0; 
  color: #fff;
}
<div>
  <label for="txtNome">Nome:</label>
</div>
<div>
  <input type="text" id="txtNome" name="txtNome" onkeyup="valida()" size="50" maxlength="100" />
  <p class="aviso" id="avisoTxtNome" style="display:none;">Este campo não pode ficar vazio!</p>
</div>
    
14.02.2016 / 16:30