Javascript - How to input back to normal state after validation

Asked

Viewed 1,648 times

1

I am working on a form which if the person does not fill in the fields, the <input> gets a red border, and at the bottom appears the name "Required field".

Everything is working fine, but I need that when the person fills the field he returns to his normal state, without red border and without the name that is inserted "Mandatory field". 'Cause he shows up, but he doesn’t disappear!


Before inserir a descrição da imagem aqui
After - Wrong inserir a descrição da imagem aqui
Then - How it should look inserir a descrição da imagem aqui
The <form> is as follows:

    <form class="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
}
}
  • What recent changes? You changed the question?

  • Yes, I had not put the email script, and the user of the previous reply is not a very frequent user.

  • The problem is that you cannot change the question and invalidate the answers given. The question asked and answered must remain the same. The amendment creates a problem.

  • But I warned the other friend, but he disappeared days ago. Then he went unanswered.

  • 3

    He gave the answer, closed it. You want something different, you have to open a new question. Editing to change the content of the question and asking people to update their answers is not a valid option.

  • I’ll stop right there.

  • 2

    You actually have to ask the full question at once. If it was a new user, I would understand, but I think I can see that here is a site of objective questions and objective answers, and not "progressive consulting" right? : P

Show 2 more comments

2 answers

6

Follow a somewhat more generic implementation, including you can include 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>

  • Friend, there is only one detail, the form is a little big, when I click to send it appears the validation messages, but it does not go up the screen, the person has to go up manually. How to fix this little problem? :)

  • Your answer is perfect, very good!

  • 1

    @Alexandrelopes, you can give Focus in error input, but in the example above it validates all inputs when performing Submit, so you would have to choose an input to receive Focus, the other option is to create a Summary.

  • How do I create this Summary? I’m not very good with JS, rsrsrs

  • 1

    @Alexandrelopes, a Summary is basically a <ul> containing the errors.

  • Give me this strength ai friend, kkkkkk, I have no idea how to do :/ Edit ai ;) Please

  • Like this, when the person sends it, it goes up to the first one <p class="validation-msg help-block ng-binding">Campo obrigatório</p> that he finds, Sakas?

  • It would be an interesting alternative :D

  • 2

    @Alexandrelopes performed an edition, now it will give Focus in the first input.

  • 3

    Thank you so much! You’re a beast! I still can’t give you the +50 because it only unlocks after 8 hours, but I already gave you the answer as sure. It was great! Congratulations on your knowledge, and for trying to help the next :D

Show 5 more comments

4


You can do this in two ways:

1 - Check otherwise

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

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 on 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 this case, it was the fact that he had the id "textile-" + the field ID. The argument of the function valida_form(form) now is the form, as you can see. And all input that you want to enter the validation must have the class .required.

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

DEMO

  • Is it possible to regulate minlenght by some date-=" " in HTML? Type the line var minLength = 5;

  • @Alexandrelopes, give, just delete the line var minLength = 5; and add within the function minLength of the object isvalid that line: var minLength = parseFloat(input.getAttribute('data-minlength')) || 3;. Now I think I’d better delete the old rsrs comments

  • Please avoid long discussions in the comments; your talk was moved to the chat

  • Thank you so much for the strength Samir, my congratulations on your knowledge, and thank you for helping people like me, kkkkk... You are a great person. Thank you! :)

  • @Samirbraga Samir, it is possible to determine which text error will appear for some data-=" " in HTML? Type o (Required field).

Browser other questions tagged

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