Is there any way to prevent input type=number getting negative values?
Use the min
attribute like this:
<input type="number" min="0">
How to prevent a user from entering negative values in Html input
Due to the <input type="number">
still not being widely well supported, you are still better off using a text input. Preventively you could disallow any characters which are not numbers with the keypress
event and e.preventDefault()
. However be sure that if you want to support legacy browsers (IE8-), there are a number of inconsistencies to take into account regarding returned key codes/ char codes. If you also want to disallow pasting non-number content, you can do so with the paste
event and e.clipboardData.getData('plain/text')
(for a complete implementation see here)
Test with the code below:
var myInput = document.getElementsByTagName('input')[0];myInput.addEventListener('keypress', function(e) { var key = !isNaN(e.charCode) ? e.charCode : e.keyCode; function keyAllowed() { var keys = [8,9,13,16,17,18,19,20,27,46,48,49,50, 51,52,53,54,55,56,57,91,92,93]; if (key && keys.indexOf(key) === -1) return false; else return true; } if (!keyAllowed()) e.preventDefault();}, false);
// EDIT: Disallow pasting non-number contentmyInput.addEventListener('paste', function(e) { var pasteData = e.clipboardData.getData('text/plain'); if (pasteData.match(/[^0-9]/)) e.preventDefault();}, false);
<input type="text">
Prevent negative inputs in form input type=number?
This uses Javascript, but you don't have to write your own validation routine. Instead just check the validity.valid
property. This will be true if and only if the input falls within the range.
<html><body><form action="#"> <input type="number" name="test" min=0 oninput="validity.valid||(value='');"><br> <input type="submit" value="Submit"></form></body></html>
How to prevent a user from entering negative values in Html input
Due to the <input type="number">
still not being widely well supported, you are still better off using a text input. Preventively you could disallow any characters which are not numbers with the keypress
event and e.preventDefault()
. However be sure that if you want to support legacy browsers (IE8-), there are a number of inconsistencies to take into account regarding returned key codes/ char codes. If you also want to disallow pasting non-number content, you can do so with the paste
event and e.clipboardData.getData('plain/text')
(for a complete implementation see here)
Test with the code below:
var myInput = document.getElementsByTagName('input')[0];myInput.addEventListener('keypress', function(e) { var key = !isNaN(e.charCode) ? e.charCode : e.keyCode; function keyAllowed() { var keys = [8,9,13,16,17,18,19,20,27,46,48,49,50, 51,52,53,54,55,56,57,91,92,93]; if (key && keys.indexOf(key) === -1) return false; else return true; } if (!keyAllowed()) e.preventDefault();}, false);
// EDIT: Disallow pasting non-number contentmyInput.addEventListener('paste', function(e) { var pasteData = e.clipboardData.getData('text/plain'); if (pasteData.match(/[^0-9]/)) e.preventDefault();}, false);
<input type="text">
Preventing user from entering negative numbers in input elements with number type
You were only adding the event listeners to the first number input.
https://jsfiddle.net/tpsbnp9q/5/
var myInput = document.querySelectorAll("input[type=number]");
function keyAllowed(key) {
var keys = [8, 9, 13, 16, 17, 18, 19, 20, 27, 46, 48, 49, 50,
51, 52, 53, 54, 55, 56, 57, 91, 92, 93
];
if (key && keys.indexOf(key) === -1)
return false;
else
return true;
}
myInput.forEach(function(element) {
element.addEventListener('keypress', function(e) {
var key = !isNaN(e.charCode) ? e.charCode : e.keyCode;
if (!keyAllowed(key))
e.preventDefault();
}, false);
// Disable pasting of non-numbers
element.addEventListener('paste', function(e) {
var pasteData = e.clipboardData.getData('text/plain');
if (pasteData.match(/[^0-9]/))
e.preventDefault();
}, false);
})
How to avoid negative numbers in html input?
You can use min property
<input type="number" min="0" name="amount" placeholder="0.001" step="0.001" required>
How to prevent user from entering negative number in react?
Handling Empty Input & Negative Numbers
// Converting App into Class-Component
class App extends React.Component {
// Set State
constructor(props) {
super(props);
this.state = {
number: ""
};
}
render() {
return (
<div className="App">
<input
type="number"
min="0"
step="1"
onChange={(e) => {
let val = parseInt(e.target.value, 10);
if (isNaN(val)) {
this.setState({ number: "" });
} else {
// is A Number
val = val >= 0 ? val : 0;
this.setState({ number: val });
}
}}
className="w-100"
// Assign State
value={this.state.number}
/>
</div>
);
}
}
How to block negative values in Input tags while entering in forms
Our conditions are:
- Positive Numbers
- Integers only (non-decimals)
We should handle:
- Mouse events
- Keyboard events
For mouse events, we will cover it with input
API as normal HTML element, by using min={0}
and step={1}
.
For keyboard events, the trick is to prevent press event on invalid input.
So we will try and rewrite this plain HTML as React DOM element:
<input type="number" onkeypress="return event.charCode >= 48" min="0" step="1" />
export default function App() {
return (
<input
type="number"
min={0}
step={1}
onKeyPress={(event) => {
if (event.charCode < 48) {
event.preventDefault();
}
}}
/>
);
}
Related Topics
Html Text Input Field With Currency Symbol
Force HTML Content to Fit in Device Width With Wkwebview
Html - How to Scroll Vertical in Select Box
Make First Column Fixed and Next Column Scrollable in HTML Table
How to Disable an Input Dynamically With Angular 7
Line Break in HTML Select Option
Background Size for Mobile Devices
Maxlength Ignored for Input Type="Number" in Chrome
Bootstrap Row With Columns of Different Height
How to Align Content of a Div to the Bottom
Why Is Percentage Height Not Working on My Div
How to Make an Element Width: 100% Minus Padding
Post Unchecked HTML Checkboxes
How to Select an Element With Multiple Classes in Jquery
What Are the Default Margins For the HTML Heading Tags (≪H1≫, ≪H2≫, ≪H3≫, etc.)
How to Set Max-Length in an Html5 "Input Type=Number" Element