1

I have trouble restricting the input characters to integers only. Is there a way by which I can restrict the decimal numbers or float from being entered into the input type="number"?

I have also tried the following approach by replacing . with '' whenever event for keyup is fired:

$("#myForm").on('submit', function(e) {
  e.preventDefault();
});

$("#number").on('keyup', function() {
  var regex = new RegExp(/\d+\.\d?/g);
  var number = $(this).val();
  if (regex.test(number)) {
    number = number.replace(/\./g, '');
    $(this).val(number);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm" action="//google.de">
  <p>Input type number step 1</p>
  <input type="number" name="number" id="number" step="1" min="0"/>
  <input type="submit" />
</form>

With the above code, following are the case results:

WORKS:
2.3

FAILS:
2..3
2….3
2.3.3.3.3.3.3.3.3.3.3.333...3

I need only 2 (any integer) to be allowed, and from all other cases (including the copy and paste), the decimal should be removed.

So my final question is that how can I restrict float numbers from being entered in the input field with type="number"? If that's not possible then how can I change the above code to meet my requirements?

EDIT:

Please do not close this question if this question partially matches another. I have written a code here too. I want to know, what's wrong with it.

Code_Ninja
  • 1,729
  • 1
  • 14
  • 38
  • I still haven't found out what's wrong with the above code @Andreas. What's the point in closing a question that partially matches another question. – Code_Ninja Sep 02 '19 at 09:09
  • try the following (returns integers only): var res = number.replace(/\D/g, ""); – Vince Sep 02 '19 at 09:16
  • You don't need JavaScript for this. Neither Firefox, nor Chrome nor IE (10+) allow me to submit the form if the value isn't an integer just by adding `step="1"`: https://jsfiddle.net/zrgoh7fx/ – Andreas Sep 02 '19 at 09:40
  • @Andreas, if you could just look into the code that I have shared, then you would know that I have already added `step` and `min` to it. But, my concern here is to block the decimal point right at the moment when the user types `.`. – Code_Ninja Sep 02 '19 at 09:48

0 Answers0