Accept only multiples of X in input

Asked

Viewed 2,842 times

2

I need my input to only accept multiples of an X value that will be defined via the function parameter. How can I proceed?

  • 1

    Better make that check on onblur, for while the user is typing the value Change between valid and invalid several times. When calculating, you know: turn the input value into a number and see if the rest of the division (%) for the other is zero.

2 answers

4

You can use HTML5 validation with a input of the kind number which already automatically validates the field and does not let the user submit the form if the entered value is not numerical.

Using the method setCustomValidity(mensagem) you can specify a validation with a custom error message. To indicate that there is no error, simply call setCustomValidity() passing an empty string as parameter.

The pseudo-class :invalid is added to the HTML5 element that does not pass validation. In CSS you can use the selector input[type="number"]:invalid to apply a specific style to erroneous elements.

Working example:

$(function(){
  // deve ser múltiplo
  var mult = 4;
  
  $('#num').keyup(function(){
    var val = parseInt($(this).val());

    if(val % mult != 0) {
      // [0] aqui é usado para acessar diretamente o elemento DOM, já que o método setCustomValidity é não é do jQuery
      $(this)[0].setCustomValidity("Digite um múltiplo de " + mult + ".");
    } else {
      $(this)[0].setCustomValidity("");
    }
  });
});
input[type="number"]:invalid {
  background-color: #f2dede;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="number" value="" id="num" /><br />
  <button>Enviar</button>
</form>

3


You can do in the event blur of input, which checks every time it loses the phocus:

var X = 2;

$("#entrada").blur(function() {
  var numero = parseInt($(this).val());
  if (!isNaN(numero)) {
    if (numero % X === 0) {
      $("#saida").html("É múltiplo de " + X );
    } else {
      $("#saida").html("Não é múltiplo de " + X );
    }
  } else {
    $("#saida").html("Entrada não é um número.");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="entrada">
<p id="saida"></p>

Browser other questions tagged

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