Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 679
Giulia Avatar asked Aug 09 '18 14:08

Giulia


People also ask

How do you check if input is a number in React?

To check if an input's value is a valid number in React: Check if the input's value is not an empty string or contains only spaces. Pass the value to the isNaN() function. If isNaN returns false , the value is a valid number.

How do you validate a number field?

Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.

How do you limit input numbers in React?

Use the maxLength prop to set a character limit on an input field in React, e.g. <input maxLength={5} /> . The maxLength attribute defines the maximum number of characters the user can enter into an input field or a textarea element.


1 Answers

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>
like image 62
Tholle Avatar answered Oct 12 '22 12:10

Tholle