How to Make a Mask for Field Validation

Asked

Viewed 399 times

1

How can I make a chew for a field where the usurer is not this low standard

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

decimal values always within quotation marks and separated by comma

if typed wrong show message

  • Got boy ?

  • See if my answer is what you need.

2 answers

1

You can use the library jQuery-Mask-Plugin, and use Regular Expressions to check the field value. 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>
<script src="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:

  • '
    Allows simple quotes
  • \d{1}
    Allows only one digit after quotation marks.
  • .
    Allows a point.
  • \d{2}
    Allows only two digits after the point.
  • ,?
    Allows an optional comma after quotation marks.
  • |(\d+)|(\')
    Recovers the rest of the value that the user typed, to verify this filled correctly.

0

See if this can 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;">
  • Partner didn’t roll here. something else these values var $array = ["'0.50'","'0.60'","'0.70'"]; not to compare is just to show that any other value will have to be inside quotation marks and separated by comma

  • You need to create your own validation code, with regular expressions, or something like that.. I just gave you an idea of what you can do..

Browser other questions tagged

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