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"/> 

Script:

$('body').on('focus',".money", function(){
        $(this).simpleMoneyFormat();
    });

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 (){
        clearTimeout(timer);
        timer = setTimeout(function (event) {
            $('input').val(Number($('input').val()).toFixed(2))
        }, 1000);
    });
    

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

    https://jsfiddle.net/usdf1nx6/

  • 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)) {
        input.style.borderColor = '#080'; // indicates correct input
      } else {
        input.style.borderColor = '#F46'; // indicates wrong input
      }
    });
    

    Demo