0

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.

0

1 Answer 1

1

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>

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

1 Comment

Glad I could help. If my answer solved your problem, click the big checkbox to accept it as the answer.

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.