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.
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.
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.
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'));
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() } />
try this
<input type="text" pattern="\d+" />
Check here :http://jsfiddle.net/b8NrE/1/
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() }
/>