19

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.

Philippe
  • 960
  • 2
  • 12
  • 29
  • Possible duplicate of [How to block +,-,e in input type Number?](https://stackoverflow.com/questions/39291997/how-to-block-e-in-input-type-number) – Sven Aug 23 '17 at 08:52
  • This url can be useful for others: https://www.xspdf.com/resolution/51724882.html – AndrewRIGHT Oct 22 '20 at 13:57

9 Answers9

31

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() } />
Jeff C
  • 311
  • 3
  • 3
15

Here is the best validation which I use.Any symbol which not a number we remove with 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.

 // Outside of function
 const exceptThisSymbols = ["e", "E", "+", "-", "."];

 //..
  return (
    <div className="App">
      <input
        type="number"
        onKeyDown={e => exceptThisSymbols.includes(e.key) && e.preventDefault()}
      />
    </div>
  );

Codesandbox demo.

Randall
  • 2,414
  • 3
  • 35
  • 63
3

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.

Boky
  • 11,554
  • 28
  • 93
  • 163
3

Here is a pretty robust solution to prevent the characters that are not numbers ("e", ".", "+" & "-") !

import React, { Component } from "react";

class MyComponent extends React.Component {
   state = { numInput: "" };

   handleChange = (e) => {
      this.setState({ [e.target.name]: e.target.value });
   }

   formatInput = (e) => {
     // Prevent characters that are not numbers ("e", ".", "+" & "-") ✨
     let checkIfNum;
     if (e.key !== undefined) {
       // Check if it's a "e", ".", "+" or "-"
       checkIfNum = e.key === "e" || e.key === "." || e.key === "+" || e.key === "-" ;
     }
     else if (e.keyCode !== undefined) {
       // Check if it's a "e" (69), "." (190), "+" (187) or "-" (189)
       checkIfNum = e.keyCode === 69 || e.keyCode === 190 || e.keyCode === 187 || e.keyCode === 189;
     }
     return checkIfNum && e.preventDefault();
   }

   render(){
     return (
       <input 
         name="numInput" 
         value={ this.state.value } 
         onChange={ this.handleChange }
         onKeyDown={ this.formatInput }  // this is where the magic happen ✨
       />
   }
}

export default MyComponent;
JulienRioux
  • 2,853
  • 2
  • 24
  • 37
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.preventDefault() }
/>
zishe
  • 10,665
  • 12
  • 64
  • 103
jgard
  • 11
  • 1
0
const PhoneInputHandler = (e) => {
        let phone=e.target.value;
        
        if(e.nativeEvent.data>=0 && e.nativeEvent.data<=9)
        {
            setStudentData({...StudentData,phone:phone})
            setValidationRules({...validationRules,phone: validatePhone(e.target.value)})
        }
        
    }
<div class="px-3 paddedInput mb-2" >
      <input class="mb-1 form-control smalltext" type="number"  name="phone" value={StudentData.phone}
                             onChange={(e)=> {PhoneInputHandler(e);}} placeholder="Enter Phone Number" /> 
      <span className="err">{validationRules.phone}</span>
</div>
0

This will help to prevent handling arrows and e. If you want you can add other possible keys, e.g. [".","+","-"].

Here is an example-

onKeyDown={(e) =>
  ["ArrowUp", "ArrowDown", "e", "E"].includes(e.key) && e.preventDefault()
}
David Mason
  • 2,917
  • 4
  • 30
  • 45
sarvan
  • 1
  • 2
-2

You can simply use onKeyDown this way:

  onKeyDown={event => {
    if (event.key == "." || event.key === "-") {
      event.preventDefault();
    }
  }}
Mahmoud Abd AL Kareem
  • 615
  • 2
  • 10
  • 23
-3

try this

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

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