Javascript - How to make input return to its normal state after validation

1

I'm working on a form which if the person does not fill in the fields, the <input> is left with a red border, and below is the name "Required field".

It's working fine, but I need it when the person completes the field it returns to its normal state, without red border and without the name that is inserted "Required field". Well it appears, but do not disappear after it's filled!

 Before  After-Wrong  After-Howtostay The<form>isasfollows:
<formclass="form-horizontal" id="formulario" name="formulario" method="get" 
action="http://localhost/br/p/124678139/" onsubmit="return valida_form(this)"></form>

My Javascript code:

function valida_form (){
if(document.getElementById("nome").value.length < 3){
document.getElementById("nome").focus();
document.getElementById("nome").style.border = "1px solid #ef3c59";
document.getElementById("textinho").innerHTML='<p class="help-block ng-binding" style="color:#ef3c59;">Campo obrigatório</p>';
return false
}
}

I also need to make it work in the email field, in which I use the following code:

function valida_form (){
var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if(!filter.test(document.getElementById("emaile").value)){
document.getElementById("emaile").focus();
document.getElementById("emaile").style.border = "1px solid #ef3c59";
document.getElementById("textinho2").innerHTML='<p class="help-block ng-binding" style="color:#ef3c59;">E-mail inválido</p>';
return false
}
}
    
asked by anonymous 28.08.2016 / 01:39

2 answers

4

You can do this in two ways:

1 - Check otherwise

You use if to check and display messages, use else to hide it:

var input = document.getElementById("nome");
function valida_form(){
  if(input.value.length < 3){
    input.focus();
    input.style.border = "1px solid #ef3c59";
    document.getElementById("textinho").innerHTML = '<p class="help-block ng-binding" style="color:#ef3c59;">Campo obrigatório</p>';
    return false
  }else{
    document.getElementById("textinho").innerHTML = ''; // ou display: none
    input.style.border = "1px solid #999";
  }
}
input.onkeyup = valida_form;
<input type="text" id="nome"><br>
<span id="textinho"></span>

2 - Use blur event - UPDATE

You hide a text in the Blur event (focus the input):

var inputNome = document.getElementById("nome");
var inputEmail = document.getElementById("email");

function valida_form(e){
  var input = e.target; // captura o elemento em questão
  // texto = captura do texto com ID igual a "textinho-"+ID do input
  var texto = document.getElementById("textinho-"+input.id); 
  if(input.value.length < 3){
    input.focus();
    input.style.border = "1px solid #ef3c59";
    texto.innerHTML = '<p class="help-block ng-binding" style="color:#ef3c59;">Campo obrigatório</p>';
    return false
  }
  input.addEventListener('blur', function(){
    if(input.value.length >= 3){
      texto.innerHTML = ''; // ou display: none
      input.style.border = "1px solid #999";
    }
  })
}
inputNome.addEventListener('keyup', valida_form);
inputEmail.addEventListener('keyup', valida_form);
Nome: <input type="text" id="nome"><br>
<span id="textinho-nome"></span>
<br>
Email: <input type="text" id="email"><br>
<span id="textinho-email"></span>

3 - Prevent Submit

Example preventing submission:

Note: I always put the warning text with some reference that becomes automatic, in the case, it was the fact that it has id "textinho-" + field ID . The argument of the valida_form(form) function is now the form, as you can see. And all% w_that you want to enter validation must have the class input .

Code: You insert new form validation rules into the .required object, which is used for checks, and the "valid" or "invalid" styles and functions in the isValid object.

DEMO

    
28.08.2016 / 02:32
6

Here is a slightly more generic implementation, including other validation rules, such as minimum, maximum, etc.

var InputValidation = function (input) {
  var that = this;

  this.input = input;
  this.msg = document.createElement("p");
  this.msg.classList.add("validation-msg");
  this.msg.classList.add("help-block");
  this.msg.classList.add("ng-binding");
  this.input.parentElement.insertBefore(this.msg, this.input.nextElementSibling);

  this.refInvalidInput = function (event) {
    that.isValid();
  }
}

InputValidation.patterns = {};
InputValidation.patterns.email = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i;

InputValidation.prototype.isValid = function (event) {
  if (this.input.dataset.required && !this.input.value.trim())
  {
    this.input.classList.add("invalid");
    this.input.addEventListener("input", this.refInvalidInput);
    this.msg.textContent = this.input.dataset.required;  
    return false;
  }

  if (this.input.dataset.email && this.input.value.trim() && !InputValidation.patterns.email.test(this.input.value))
  {
    this.input.classList.add("invalid");
    this.input.addEventListener("input", this.refInvalidInput);
    this.msg.textContent = this.input.dataset.email;  
    return false;
  }

  this.input.classList.remove("invalid");
  this.input.removeEventListener("input", this.refInvalidInput);
  return true;
}

var FormValidation = function (form) {
  var that = this;
  var inputs = form.querySelectorAll(".validation");
  
  this.form = form;
  this.inputs = [].map.call(inputs, function (input, indice) {
    return new InputValidation(input);
  });

  this.form.addEventListener("submit", function (event) {
    that.onFormSubmit(event);
  });
}

FormValidation.prototype.onFormSubmit = function (event) {
  var erros = this.inputs.filter(function (entry, indice) {
    return !entry.isValid();
  });
  if (erros.length > 0) {
    erros[0].input.focus();
    event.preventDefault();
  }
}

var form = document.getElementById("form");
form = new FormValidation(form);
.validation + .validation-msg {
  display: none;
}

.validation.invalid + .validation-msg {
  display: block;
  color: #ef3c59;
}

.validation.invalid {
  border: 1px solid #ef3c59;
}
<form id="form">
  <div>
    <label>
      Texto:
      <input id="texto" type="text" class="validation"
             data-required="Campo Obrigatório" />
    </label>
  </div>
  <div>
    <label>
      Email:
      <input id="texto" type="text" class="validation"
             data-email="Email Invalido"
             data-required="Campo Obrigatório" />
    </label>
  </div>
  <div>
    <label>
      <input id="enviar" type="submit" />
    </label>
  </div>
</form>
    
31.08.2016 / 14:38