Explain Codes LogoExplain Codes Logo

Is there any way to prevent input type="number" getting negative values?

html
input-validation
form-validation
accessibility
Anton ShumikhinbyAnton Shumikhin·Feb 25, 2025
TLDR

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:

<input type="number" min="0" onkeydown="return event.key !== '-';"> <!-- 'Min' stands for minions. Sorry, no 'negative' minions allowed! -->

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:

<input type="number" min="0" oninput="this.value = Math.abs(this.value)"> <!-- It's like our input field took an absolute value filter. No negatives here! -->

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:

<input type="number" onkeypress="return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 8 || event.charCode === 0"> <!-- This makes our field a VIP digits-only club. No signs (-/+) allowed at the entrance! -->

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:

<input type="number" onkeydown="return (event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 95 && event.keyCode < 106) || event.keyCode === 8"> <!-- Imagine our input is a basketball hoop and we're blocking all shots from outside the numeric range. Slam dunk! -->

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:

<input type="number" min="0" oninput="this.validity.valid||(this.value='');"> <!-- It's like our field has a self-cleaning mode, it reverts back to the pristine state upon getting invalid entries. Neat! -->

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:

  1. Disable mouse wheel and increment/decrement buttons — some browsers allow scrolling to alter number input:

    <input type="number" min="0" onwheel="this.blur()" onclick="this.blur()"> <!-- Who said form field can't have its own 'do not disturb' mode? Not us! -->
  2. Use a custom validation message for a refined user experience:

    var numberInput = document.querySelector('input[type="number"]'); numberInput.oninvalid = function(ev){ ev.target.setCustomValidity('Please enter a positive number.'); /* Custom message, because our field deserves its own voice, right? */ }; numberInput.oninput = function(ev){ ev.target.setCustomValidity(''); /* And now it went silent, because it's full of valid, positive numbers. Way to go! */ };

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.