Is there any way to prevent input type="number" getting negative values?
Ensure only positive numbers for <input type="number">
by setting the min
attribute to 0
. Apply a JavaScript event listener
to block the '-' key.
Snippet:
This snippiet keeps min
value at zero and uses JavaScript to limit input, barring any negative values.
Enforcement of positive numeric input
Instant correction of negatives can be implemented using the oninput
event and applying Math.abs
to ensure input remains non-negative:
This direct approach benefits the user experience by stopping those pesky negatives before they cause annoying form errors.
Permit only numeric characters
Restrict entries to only digits with an onkeypress
event handler. This method also isolates and handles exceptions like backspace or arrow keys:
This ensures only numeric values from the number row and Numpad, promoting clean, error-free data.
Block irrelevant keys
Expand the onkeypress
approach and use onkeydown
to strike out irrelevant keystrokes outside of the 48-57 (number row) and 96-105 (Numpad) ranges, excluding functional keys like backspace:
This creates a solid defense against unwanted inputs, minimizing user error.
Using validity.valid for elegant validation
Shift from blocking negatives toward correcting them using validity.valid
, or set value
to an empty string ''
when input is invalid:
By leveraging HTML5 form validation, the input
value reverses to the last valid state or empties upon invalid entry, enforcing no-negative rules smoothly and unobtrusively.
Strengthening input limitations
Sometimes users might paste a negative value or use increment/decrement buttons that may lower the value below zero. To manage these scenarios:
-
Disable mouse wheel and increment/decrement buttons — some browsers allow scrolling to alter number input:
-
Use a custom validation message for a refined user experience:
These adjustments ensure a seamless user-friendly experience while maintaining strict data input.
Focus on accessibility and performance
Prioritize accessibility and performance as you reinforce non-negative numbers restriction. Test your form fields on multiple devices, including those with keyboard, screen readers, and mobile devices, ensuring suitability for all users.
Ensure clear visual indication for an error state and provide alternative text for screen readers with aria
labels amongst other accessibility best practices.
Was this article helpful?