Prevent Negative Number in Input Type Number

1. JavaScript (external) — Block – key

This input uses external JavaScript to prevent minus sign entry. The event listener watches for ‘keydown’ events and blocks specifically the ‘-‘ key or ‘Minus’ key from being entered.

2. HTML Only — min=”0″

This input uses only HTML attributes to prevent negative numbers. The min=”0″ attribute ensures the number can’t go below zero, though users can still type a minus sign (it will be removed when focus leaves the field).

3. Inline JavaScript — onkeydown in HTML

This input uses inline JavaScript to block minus signs immediately on key press. Similar to the first example but implemented directly in the HTML markup rather than through an external script.

4. Block – on Paste Too

This input extends the protection by preventing both typing minus signs AND pasting text that contains minus signs. It checks clipboard data during paste events and blocks if a minus is detected.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.