How To Restrict Negative and Decimals From input type number


We will handle this use-case using Javascript. When we use input type="number" we are aware to use attributes such as min and max to set the limit as required. Restricting negative numbers using min="0" is the widely used approach. It restricts the numbers less than the specified entry in min attribute using the arrow. But one fallback for that approach is that the user can still type any number which is less than the min attribute value or more than the max attribute value.

<input type="number" min="0" name="testInput">


The simple solution for solving this issue is that we will use onInput event attribute of the input field. This event gets fired when the user gives input to the element. This event fires immediately after the user input has changed. We will check if the user input is valid, otherwise, we will set it to empty. The below solution will restrict negative numbers, decimal numbers, and numbers greater than the maximum value specified. 

<input type="number" [min]="0" [max]="1100" name="testInput" onInput="validity.valid || (value='');">