user9074131
user9074131

Reputation: 73

Allow only numbers in React by onKeyPress or onKeyDown

I need the user to enter only numbers in the input field. I tried by using onKeyPress & onKeyDown Events. I am unable to get the boolean values form the Events .Any help would be appreciated.

class User extends Component {
  constructor (props) {
    super(props)
    this.state = { value: ''}
    this.keyPress = this.keyPress.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(e) {
    this.setState({ value: e.target.value });
 }
  keyPress(e){
    if(e.keyCode == 13){
       console.log('value', e.target.value);
       }
    else{
      const charCode = (e.which) ? e.which : e.keyCode;
      if (charCode > 31 && (charCode < 48 || charCode > 57)){
        return false;
      }
      else{
         return true;
      }
    }
 }
<input
 type='text'
 value={this.state.value}
 onKeyDown={this.keyPress(event)}
 onChange={this.handleChange}
 />

Upvotes: 1

Views: 5551

Answers (2)

Jo&#227;o Cunha
Jo&#227;o Cunha

Reputation: 10307

You can always use input type="number". It doesn't allow any letters.

If you are going to use masks then you can try this

As you can see in the snippet you can restrict the mask for numbers with the char: 9 and even specify a char that sits between spaces.

class App extends React.Component {
  render() {
    return <ReactInputMask mask="999 999 999" maskChar="_" />;
  }
}

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>
<!-- Will be exported to window.ReactInputMask -->
<script src="https://unpkg.com/react-input-mask/dist/react-input-mask.min.js"></script>

<div id="root"></div>

Upvotes: 0

Gibby
Gibby

Reputation: 221

Use input type="number". It restricts the user to just writing numbers

Upvotes: -1

Related Questions