ReactJs prevent e and dot in an input type number ReactJs prevent e and dot in an input type number reactjs reactjs

ReactJs prevent e and dot in an input type number


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


Here is the best validation which I use.Any symbol which not a number we remove in replace method.Input type need to be text.In other cases it can work unexpectedly.

  const [val, setVal] = useState("");  return (    <div className="App">      <input        type="text"        value={val}        onChange={e => setVal(e.target.value.replace(/[^0-9]/g, ""))}      />    </div>  );

Codesandbox demo.

If you not good with regexp alternatively you can use second variant.

const [symbolsArr] = useState(["e", "E", "+", "-", "."]);  return (    <div className="App">      <input        type="number"        onKeyDown={e => symbolsArr.includes(e.key) && e.preventDefault()}      />    </div>  );

Codesandbox demo.


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.