Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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}/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...