Ad Code

HTML text input allow only numeric input

Here is a simple one which allows for exactly one decimal, but no more. The input event uses regex to replace text on the fly based on the two patterns:

  1. Remove anything that's not a digit or a dot
  2. Remove any second instance of a dot


<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" />

As someone commented below, the solution above does not handle leading zeros. If your particular use case requires that these are not allowed you can add to the pattern above like so:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />

 

That will allow 0.123 or .123 but not 0123 or 00.123.


 

Post a Comment

0 Comments