Home > Software engineering >  how use onPaste in antD inputNumber Field to prevent input other than integers
how use onPaste in antD inputNumber Field to prevent input other than integers

Time:09-20

I was using antD in my react project, I was using inputNumber Component of antD to get input, all I wanted is integer input and wanted to prevent all the other input from all source such as copy-pasting, keyboard. is there any way to do this?

CodePudding user response:

you should define a state variable for the input value as

const [userInput, setUserInput] = React.useState('');
onChange={(e) => {
    //remove letters from input
    setUserInput(e.target.value.replace(/[^0-9]/g, ''))

}}

you can use this approach but it will set the value without the letters if the value is something like "user123" -> "123"

if you want to prevent the input to act even if 1 letter exists, then you can use like this:

onChange={(e) => {
      // test regexp to prevent letters
      const regex = new RegExp('^[0-9] $');
      if(regex.test(e.target.value)) {
        setUserInput(e.target.value);
      }
    }}
  • Related