ExtraSun
ExtraSun

Reputation: 548

React.JS How to allow only digits to be typed in input with 'onKeyPress'

I'm working on my ReactJS new website and I want the input to allow the user to type only digits for mobile number.

  onlyNumberKey = (event) => {
    let ASCIICode = event.which ? event.which : event.keyCode;
    if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57)) 
    return false;
    return true;
  };

 <div>
    <input type='text' onKeyPress='return {this.onlyNumberKey}' />
    </div>

I use the "onlyNumberKey" function I found in many sites I discovered for my question.
This fuction is working and will well return true or false as needed,
but I probably don't understad, how to prevent letters and special chars from being insert by the user ?

This wont work and gives an error -

 onKeyPress='return this.onlyNumberKey' 

"Warning: Expected onKeyPress listener to be a function, instead got a value of string type."
And I know why, just to clear that I tried many solutions.

Thanks for the helpers

Upvotes: 0

Views: 1609

Answers (2)

Vahid Alimohamadi
Vahid Alimohamadi

Reputation: 5868

Isn't better to validate as usual?

const {useState} = React;

const r = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/

const PhoneInput=() => {
   const [value,setValue]=useState(null);
   const [validated,setValidated]=useState(false);
   
   const onChange=(e)=>{
    e.preventDefault();
    let v = e.target.value;
    setValidated(!!v.match(r));
   };
   return (
       <fieldset>
        <input
           type="text"
           value={value}
           onChange={onChange}
        ></input>
        <button disabled={!validated}>
          Send
        </button>
       </fieldset>
   );
};

ReactDOM.render(<PhoneInput />,document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 0

tevemadar
tevemadar

Reputation: 13225

You could just filter out the unwanted characters in a change handler:

class Test extends React.Component {
  constructor(){
    super();
    this.state = {
      input: ''
    };
  }

  onChangeHandler(e){
    this.setState({
      input: e.target.value.replace(/\D/g,'')
    });
  }

  render (){
    return (
      <input value={this.state.input} type="text" onChange={this.onChangeHandler.bind(this)}/>
    );
  }
}

ReactDOM.render(
  <Test />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions