Help with a Javascript mask for a form

Asked

Viewed 35 times

0

One of the form fields requires the following validation:

It must contain 6 numbers, the last of which must be the result of the sum of the others. If this sum is greater than 10, all digits of the result must be added up until the new result meets this requirement. If the sum is 10, the value considered for the sixth number of the "Registration number" is 0.

HTML:

Número de Registro:<br >< input type="text" name="registro" onblur="validaRegistro(this.value)">< div id="m3">< /div>

Javascript:

function validaRegistro(value) {
  var padrao = /^[0-9]+$/;
  if (value.match(padrao)){
    document.getElementById("m3").innerHTML="<font color='green'>Ok!</font>";
  } 
  else {
    document.getElementById("m3").innerHTML="<font color='red'>Campo incorreto</font>";
  } 
}

1 answer

0

From what you described in the question, the code below will serve you (see comments):

function validaRegistro(value){
   var padrao = /^\d{6}$/; // só aceita 6 dígitos à partir do início
   var valida = true; // flag para validar a soma
   if(value.match(padrao)){
      var nums = value.split('').map(Number); // crio uma array com os números
      var ultimo = nums.pop(); // pego e retiro o último número da array
      var soma = 0; // valor inicial da soma
      for(var vals of nums){ // loop para somar os 5 dígitos da array
         soma += vals;
      }

      if(soma > 10){
         valida = false; // se a soma for maior que 10, invalida
      }else if(soma == 10){
         var resultado = nums.join('')+"0"; // se for igual a 10, junto a array e concateno 0
      }else{
         var resultado = nums.join('')+ultimo; // se for menor que 10, junto a array e concateno com o último dígito
      }
   }else{
      valida = false; // não atendeu ao regex
   }

   if(valida){ // se os requisitos foram atendidos
      document.getElementById("m3").innerHTML="<font color='green'>Ok!</font>";
      console.log(resultado);
   }else{ // requisitos não foram atendidos
      document.getElementById("m3").innerHTML="<font color='red'>Campo incorreto</font>";
   }
}
Número de Registro:<br>
<input type="text" name="registro" onblur="validaRegistro(this.value)">
<div id="m3"></div>

  • Thank you very much! It helped a lot!

  • I saw that you are new on the site. You know you have to choose an answer as the favorite?

  • Mark in your favorite answer. Click the icon next to the answer.

  • Took the answer and disappeared, kkk +1

  • In a is? That’s why I already see new users and already pass the tape

  • @wilhelmandreas mark the answer as accepted, see https://i.stack.Imgur.com/evLUR.png

  • 1

    @dvd saves this image link so you can use https://i.stack.Imgur.com/evLUR.png

  • @Leocaracciolo From a reputation, I think 15K, becomes "reliable user"... or is 20K, I do not remember

Show 3 more comments

Browser other questions tagged

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