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!
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With