Form validation

Asked

Viewed 55 times

-2

Create the CSS style class called "invalid", whose formatting is to have the following background color: #A00 and white text. Change the form validation so that, if a form field is invalid, assume this class. If correct, return to the standard 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
}

In other words, change Alert to what’s in html, but using these cited methods.

  • Confused... can reformulate?

  • Yes, I’ll rephrase :D

  • The way you described your question seems to me an academic exercise, I’m correct?

1 answer

0

Change the event (onkeyup) as your need (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>

Browser other questions tagged

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