I have a input box which is of type text, i wanted only to enter the numbers and it should not exceed max length of 6 in react. please give some reference on it.
1 Answer
You could use a regex and a simple .length validation. Here's an example:
class Example extends React.Component {
constructor() {
super();
this.state = { number: '' };
}
handleChange(e) {
const val = e.target.value;
if (val.length <= 6 && /^(\s*|\d+)$/.test(val)) {
this.setState({
number: val
});
}
}
render() {
return(
<input onChange={this.handleChange.bind(this)} value={this.state.number} />
);
}
}
ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
<div id="View"></div>
You could also go with the HTML5 validation, but it only checks when being submitted:
<form>
<input type="number" max="999999" />
<input type="submit" />
</form>
1 Comment
Fabian Schultz
Glad I could help. If my answer solved your problem, click the big checkbox to accept it as the answer.