16

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!

3
  • If you use redux-form, it has a validation for your form field redux-form.com/7.4.2/examples/syncvalidation. If you do not use redux-form, you have to have an onChange handler to check wether the value is in the range or not. If it is not valid, you can set state form is invalid and disable submit event Commented Aug 9, 2018 at 15:08
  • I think you should try redux-form if you use redux in your app Commented Aug 9, 2018 at 15:09
  • Thank you, I'll have a look at redux-form as well! Commented Aug 9, 2018 at 15:24

2 Answers 2

28

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>

Sign up to request clarification or add additional context in comments.

3 Comments

How about if I need a field with decimal places? Such currency fields? I am struggling with this for hours and I can't find a solution.
Value doesn't have to beint in anyway
With this solution you are not able to delete 1 so you can not enter anything that does not start with 1.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.