Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only numbers. Input number in React

I'm trying to exclude minus and plus from input, but it's going wrong:

handleChange(event) {   const value = event.target.value.replace(/\+|-/ig, '');   this.setState({financialGoal: value}); } 

Render input code:

<input style={{width: '150px'}} type="number" value={this.state.financialGoal} onChange={this.handleChange}/> 
like image 516
lalala Avatar asked Apr 28 '17 19:04

lalala


People also ask

How do I allow only numbers in input React?

To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted. Then in the onChange handler, we only set the value of the input when the inputted value is valid.

How do I allow only numbers in input text field?

Using <input type="number"> The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.


1 Answers

I tried to mimic your code and noticed that there's an issue on React with <input type='number' />. For workaround, check this example and try it yourself: https://codepen.io/zvona/pen/WjpKJX?editors=0010

You need to define it as normal input (type='text') with pattern for numbers only:

    <input type="text" pattern="[0-9]*"      onInput={this.handleChange.bind(this)} value={this.state.financialGoal} /> 

And then to compare the validity of input:

const financialGoal = (evt.target.validity.valid) ?    evt.target.value : this.state.financialGoal; 

The biggest caveat on this approach is when it comes to mobile --> where keyboard isn't in numeric but in normal alphabetic format.

like image 91
Samuli Hakoniemi Avatar answered Sep 18 '22 11:09

Samuli Hakoniemi