Giulia
Giulia

Reputation: 807

How to validate numeric inputs in ReactJS

In Django you can easily use MinValueValidator and MaxValueValidator to validate IntergerFields.
What is the their counterparts in ReactJS?

I have a form in the frontend (built with ReactJS) where multiple fields are type=number fields and the numbers need to fit inside a specific range of values, i.e. greater than 0, smaller than 250.

In the backend, I achieved this control over the numeric input by using Min/Max ValueValidator. What shall I do in ReactJS frontend?

Thank you!

Upvotes: 16

Views: 46398

Answers (2)

This is because the onChange function expects it to be numeric. When you are entering backspace that field becomes blank which is not a valid number and it's trying to call onChange with blank value that is why you are not able to edit it

Upvotes: 0

Tholle
Tholle

Reputation: 112917

You can still use the min and max attributes for the input, but have some custom logic for checking that the input value doesn't go outside of that interval.

Example

class App extends React.Component {
  state = { value: 0 };

  handleChange = event => {
    let { value, min, max } = event.target;
    value = Math.max(Number(min), Math.min(Number(max), Number(value)));

    this.setState({ value });
  };

  render() {
    return (
      <input
        value={this.state.value}
        onChange={this.handleChange}
        type="number"
        min="1"
        max="250"
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

Upvotes: 28

Related Questions