Skip to content
Advertisement

How to prevent user from entering negative number in react?

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

<input
   type="number"
   min="0"
   step="1"                        
   onChange={this.handleChange}                        
   className="w-100"
   value= "1"
   />

Advertisement

Answer

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>
    );
  }
}
Advertisement