ReactJs prevent e and dot in an input type number

2019-06-09 15:38发布

问题:

I would like to prevent e and . to be type in an <input type="number"/>. Without jQuery or using step attribute. I've tried with pattern="[0-9]" but it's not working.

EDIT : On focus the keyboard should be a digit keyboard.

回答1:

With React you could do something like:

class Test extends React.Component {
   constructor(){
      super();
      this.state = {value: ''};
      this.onChange = this.onChange.bind(this)
   }

   onChange(e){
      const re = /^[0-9\b]+$/;
      if (e.target.value == '' || re.test(e.target.value)) {
         this.setState({value: e.target.value})
      }
   }

   render(){
     return <input value={this.state.value} onChange={this.onChange}/>
   }
}

React.render(<Test />, document.getElementById('container'));

Here is fiddle.



回答2:

I couldn't find a solution to prevent e and . to be type in an <input type="number"/> but if we use <input type="tel"/> it will show a digit keyboard when using a mobile phone and prevent e and . to be typed. Here's fiddle

class Test extends React.Component {
  constructor() {
    super();
    this.state = {
      value: ''
    };
    this.onChange = this.onChange.bind(this)
  }

  onChange(e) {
    const re = /^[0-9\b]+$/;
    if (e.target.value == '' || re.test(e.target.value)) {
      this.setState({
        value: e.target.value
      })
    }

  }

  render() {
    return <input type="tel" value={this.state.value} onChange={this.onChange} />
  }
}

React.render(<Test/>, document.getElementById('container'));


回答3:

The 'e' is the only letter that's accepted in a number field because it allows for exponents. You could use input type="text" but it doesn't give you the browser's native up and down arrows that type="number" does. And the pattern attribute validates on submission but doesn't stop someone from typing the 'e' in the first place. In REACT you can use this to completely block the 'e' key from being typed in a number input:

<input type="number" onKeyDown={ (evt) => evt.key === 'e' && evt.preventDefault() } />


回答4:

try this

    <input type="text" pattern="\d+" />

Check here :http://jsfiddle.net/b8NrE/1/



回答5:

The best way to handle this is to use the onKeyDown prop (onkeydown in plain html) to check the keyCode when the user uses the keyboard to input a character. If the keyCode for the event is 69 (for 'e') or 190 (for '.'), then you can preventDefault(), preventing the input from being displayed.

<input type="number" onKeyDown={ e => ( e.keyCode === 69 || e.keyCode === 190 ) && e.preventDafault() } />