0

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

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.