Source:  Twitter logo

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.

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() } />
26 users liked answer #0dislike answer #026
Jeff C profile pic
Jeff C

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.

5 users liked answer #1dislike answer #15
Randall profile pic
Randall

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.

3 users liked answer #2dislike answer #23
Boky profile pic
Boky

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;
2 users liked answer #3dislike answer #32
JulienRioux profile pic
JulienRioux

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() }
/>
1 users liked answer #4dislike answer #41
jgard profile pic
jgard
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 users liked answer #5dislike answer #50
Vishala Ramasamy profile pic
Vishala Ramasamy

You can simply use onKeyDown this way:

  onKeyDown={event => {
    if (event.key == "." || event.key === "-") {
      event.preventDefault();
    }
  }}
-1 users liked answer #6dislike answer #6-1
Mahmoud Abd AL Kareem profile pic
Mahmoud Abd AL Kareem

try this

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

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

-2 users liked answer #7dislike answer #7-2
Sushant Verma profile pic
Sushant Verma

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).