-2

I want to keep the input value limited to number(including -ve integers) and limit decimals to 2 digit.

Accept:

22.33; -123.45; 0.22

Reject:

-123.000123; --123.000123; -123-23.12; --23-1.00

I'm using this

<input id="restricted" type="text" class="form-control" placeholder="00.00" onkeypress="return isNumberKey(evt,this)"/>


function isNumberKey(evt, element) {
 var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46     || charcode == 8))
    return false;
  else {
   var len = $(element).val().length;
   var index = $(element).val().indexOf('.');
   if (index > 0 && charCode == 46) {
     return false;
   }
     if (index > 0) {
    var CharAfterdot = (len + 1) - index;
     if (CharAfterdot > 3) {
    return false;
  }
}

  }
  return true;
 }

I dont want it to validate. I want it not accept other than integers and limit it to 2 digit after "."

fonr
  • 47
  • 1
  • 9
  • It would be suprising if you could not find the answer easily with any web search engine – GôTô Jan 11 '17 at 06:50
  • I had found similar to my question http://stackoverflow.com/questions/2808184/restricting-input-to-textbox-allowing-only-numbers-and-decimal-point but when i try to run first codesnippet locally its not working neither in jsfiddle – fonr Jan 11 '17 at 07:01
  • 1
    Possible duplicate of [Validate decimal numbers in JavaScript - IsNumeric()](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – Reuben Mallaby Jan 11 '17 at 07:11
  • Actually this is the first time i'm using stackoverflow. And i accidentally pressed enter before completing my question i don't know if its a feature or not but it clearly didn't helped me. And it automatically got posted i wasn't able to edit it. And that post is definitely not the one that im looking for. – fonr Jan 11 '17 at 07:46

4 Answers4

1

  function isNumberKey(evt, element) {
  $('#restricted').bind("change paste keyup blur", function() {

    if(this.value.length == 1 && this.value == '-'){
      //do nothing
    }
    else{
      var retValu = testInput(this.value);

      if(retValu != '1'){
        try{
          this.value = this.value.substring(0, this.value.length - 1);
        }catch(e){

        }
      }
    }

  });
}

  
function testInput(inputValue)
{

  if (inputValue.match(/^-?[+]?[0-9]+([.][0-9]{1,2})?$/)){
    return 1;
  }
  else if(inputValue.match(/^-?[+]?[0-9]+([.])?$/)){
    return 1;
  }
  else{
    return 0;
  }

}

    testInput("22.33");
    testInput("-123.45");
    testInput("0.22");

    testInput("-123.000123");
    testInput("--123.000123");
    testInput("-123-23.12");
    testInput("--23-1.00");
1

100% working!! Enjoy it!!! And follow helping other like us!!

 <html>
     <head>
      <script>
      function replacePonto(){
        var input = document.getElementById('qtd');
        var ponto = input.value.split('.').length;
        var slash = input.value.split('-').length;
        if (ponto > 2)
                input.value=input.value.substr(0,(input.value.length)-1);

        if(slash > 2)
                input.value=input.value.substr(0,(input.value.length)-1);

        input.value=input.value.replace(/[^0-9.-]/,'');

        if (ponto ==2)
 input.value=input.value.substr(0,(input.value.indexOf('.')+3));

if(input.value == '.')
 input.value = "";
              }
      </script>
      </head>
      <body>
         <input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()">
      </body>
    </html>
0

Use HTML5 patterns.

<form action="#">
<input type="text" pattern="[\d]+" title="Numbers">
<input type="Submit" value="Validate">
</form>

Or the straight javascript variant:

var input_field = document.getElementById('the_id');

input_field.addEventListener('keyup', function() {
    var v = parseFloat(this.value);
    if (isNaN(v)) {
        this.value = '';
    } else {
        this.value = v.toFixed(2);
    }
});
<input id="the_id" placeholder="00.00" value="1234">
Ruslan Abuzant
  • 631
  • 6
  • 17
  • Should restrict it from entering alphabets. – fonr Jan 11 '17 at 07:00
  • Your pattern `\d` is not restricted enought, because is only accepts integers. It does not accept `42.42`. Also, in your JavaScript you make a round of the number. I think it wouldn't round these numbers, but only accept them or not. – Anthony Jan 11 '17 at 07:03
  • Just change `addEventListener('change'` to `addEventListener('keyup'` to prevent it from even accepting alphanumerics @fonr – Ruslan Abuzant Jan 11 '17 at 07:10
0

Should change keypress to keyup. I also update the isNumberKey() code

HTML

<input type="text">  

JS

function isNumberKey(value)    {
    console.log(value);
    var regex = /^[+-]?\d*\.?\d{0,2}$/;
    if(regex.test(value)){
       console.log("true");
       return true;
    }else{
       console.log("false");
       return false;
    }
}

$("input[type=text]").on('keyup', function(){
  if (!isNumberKey(this.value)){
     $(this).val(function(index, value){
        return value.substr(0, value.length - 1);
     });
  }
});
Hezron
  • 352
  • 1
  • 15
  • I had tried using it but i believe after d{0,2} it should only allow 2 digit after decimal right. But it is not. here is the fiddle for it. https://jsfiddle.net/rahilAhmed/ksj5f52z/ – fonr Jan 11 '17 at 07:19
  • I change `d{0,2}` to `d{0,1}`. Please try it again. It should be works. https://jsfiddle.net/hezronel/09jbu7qk/3/ – Hezron Jan 11 '17 at 07:37
  • I'm sorry but i think it compatible issue. I'm trying to open your fiddle on IE. Its not working in IE(in console it thows undefined "evt"). But when i try the same in Chrome its working. – fonr Jan 11 '17 at 07:49
  • Also as what i understand is [+-]? means only in the beginning of the string. Should not allow in the middle of it. As per the regex that's what i understood. Correct me if i'm wrong. But its accepting -+ in the middle of the string. – fonr Jan 11 '17 at 07:54
  • Its allowing in the middle of the string (-123-23-22). (https://jsfiddle.net/hezronel/09jbu7qk/3/) – fonr Jan 11 '17 at 08:05