ReactJs prevent e and dot in an input type number

2019-06-09 15:16发布

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.

5条回答
我想做一个坏孩纸
2楼-- · 2019-06-09 15:51

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() } />

查看更多
我只想做你的唯一
3楼-- · 2019-06-09 15:56

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'));
查看更多
叛逆
4楼-- · 2019-06-09 16:01

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.

查看更多
地球回转人心会变
5楼-- · 2019-06-09 16:09

try this

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

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

查看更多
迷人小祖宗
6楼-- · 2019-06-09 16:11

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() } />
查看更多
登录 后发表回答