Search code examples
reactjsvalidation

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!


Solution

  • 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>