How to allow only numeric input, allow 2 digits after decimal and allow to input minus in jquery?

I'd like to restrict users input in a form to a decimal with a maximum of two numbers after (.) And users allow to input minus. and a text field which only accepts a number.

<input type="text" name="debet[]" placeholder="debet" class=" money" value="0"/> 


$('body').on('focus',".money", function(){

Here is a jsFiddle example

Somebody can help me with this?

2 answers

  • answered 2018-11-08 08:29 Darryl Ceguerra

    <input type="number" name="debet[]" placeholder="debet" class="money"/> 
    var timer;
    $('input').keyup(function (){
        timer = setTimeout(function (event) {
        }, 1000);

    this should do, it will fire the event every 1 seconds

  • answered 2018-11-08 08:38 rv7

    You can add an event listener for blur event on input. And, then use a regex to validate the input using RegExp.test() method

    let input = document.querySelector('input'); // input element
    const checkRegex = /^\-?\d[\,\d]+\d\.\d{0,2}$/; // regex for the format: DDD,DDD.DD
    input.addEventListener('blur', evt => {
      if(checkRegex.test(input.value)) { = '#080'; // indicates correct input
      } else { = '#F46'; // indicates wrong input