I want to restrict users from entering negative values. I am using min = “0”. With this i can restrict users from decrementing to 0, i.e, users can only decrement value till 0. But they are able to type “-“. How to prevent in react js.
https://codesandbox.io/s/react-input-example-forked-xnvxm?file=/src/index.js
JavaScript
x
9
1
<input
2
type="number"
3
min="0"
4
step="1"
5
onChange={this.handleChange}
6
className="w-100"
7
value= "1"
8
/>
9
Advertisement
Answer
Handling Empty Input & Negative Numbers
JavaScript
1
36
36
1
// Converting App into Class-Component
2
class App extends React.Component {
3
// Set State
4
constructor(props) {
5
super(props);
6
this.state = {
7
number: ""
8
};
9
}
10
11
render() {
12
return (
13
<div className="App">
14
<input
15
type="number"
16
min="0"
17
step="1"
18
onChange={(e) => {
19
let val = parseInt(e.target.value, 10);
20
if (isNaN(val)) {
21
this.setState({ number: "" });
22
} else {
23
// is A Number
24
val = val >= 0 ? val : 0;
25
this.setState({ number: val });
26
}
27
}}
28
className="w-100"
29
// Assign State
30
value={this.state.number}
31
/>
32
</div>
33
);
34
}
35
}
36