How to Make a Mask for field validation

0

How can I chew a field where the user does not set this pattern down

example '0.50', '0.60', '0.70'

decimal values always within double quotes and comma-separated

if typed wrong show message

    
asked by anonymous 04.02.2018 / 18:11

2 answers

0

See if this might help you:

Javascript:

  var input = document.getElementById("input");
  var logger = document.getElementById("logger");
  var $array = ["'0.50'","'0.60'","'0.70'"];
  var i;

  function validar(){

    var $descartavel = input.value;

    for (i = 0; i < $array.length; i++) {
      if($descartavel.indexOf($array[i]) != -1){ 
        logger.innerHTML = "";
      }else{
        if(i == 10){
          i = 0;
        }
        logger.innerHTML = "Valores estão inválidos! Corrija-os por favor!";
      }
     }
  }

HTML:

     <input type="text" id="input" onkeyup="validar()"/><br/><br />

      <div id="logger" style="background:#f44336;color:#fff;">
    
04.02.2018 / 18:48
0

You can use the jQuery-Mask-Plugin library and use Regular Expressions to check the value of the field. See the example:

$(document).ready(function() {
	var campo = $('.campo');
	var alert = $('.erro');
	var mascara = "'0.00'";
	var fnc = function(v) {
		// Se o texto do campo tiver o mesmo tamanho
		// que a variável mascara, incrementa: ,'0.00' e faz o retorno,
		// caso contrário retorna o valor atual da variável mascara
		return (v.length === mascara.length) ? mascara += ",'0.00'" : mascara;
	};
	var options = {
		onKeyPress: function(v, e, f, o) {
		    console.log(v);
		    const reg = /('\d{1}\.\d{2}',?)|(\d+)|(\')/g;
		    let result = true;
		    var test = v.match(reg);
		    if (test) {
		        test.forEach(r => {
		            if (/('\d{1}\.\d{2}',?)/.test(r) === false) {
		                result = false;
		            }
		        });
		    }
		    // Verifica se o valor da variável 'result' é falso
		    // caso for exibi a mensagem, caso contrário oculta.
		    (result === false) ? alert.show(): alert.hide();
		    campo.mask(fnc(v), o);
		}
	};
	campo.mask(mascara, options);
});
.test {
    border: 2px solid #ccc;
    padding: 6px;
}
.erro {
    border: 2px solid red;
}

div.erro {
    background: #ff7675;
    border: 0;
    color: #fff;
    display: none;
    font-family: 'Verdana';
    font-size: 15px;
    margin-top: 15px;
    padding: 12px;
}
<script src="https://code.jquery.com/jquery-2.2.4.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.13/jquery.mask.min.js"></script>
<input type="text" class="campo" />
<div class="erro">Dados invalidos</div>

Explaining:

  • '
    Allow single quotes
  • \ d {1}
    Allow only one digit after the quotation mark.
  • .
    Allows a period.
  • \ d {2}
    Allows only two digits after the dot.
  • ,?
    Allows an optional comma after the quotation mark.
  • | (\ d +) | (\ ')
    Retrieve the remainder of the value that the user entered, to verify it is filled in correctly.
05.02.2018 / 07:48