Skip to content
Advertisement

I try to validate a textbox that it should not allow any string

I am trying to validate a textbox that the user should type only numbers in the textbox. Here is my code

import { useState } from "react";

export default function App() {
  const [phoneNumber, setPhoneNumber] = useState(null);
  const handleOnChange = (val) => {
    if (!isNaN(val)) {
      setPhoneNumber(val);
    }
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <input
        type="text"
        value={phoneNumber}
        onChange={(e) => handleOnChange(e.target.value)}
      />
    </div>
  );
}

https://codesandbox.io/s/kind-moon-x6il3?file=/src/App.js:0-513 If we start with the string it is not validating, it is allowing you to type the strings. If we start with numbers, it is working fine. If I change input type to number, I am facing some issue with character e. How to fix this issue?

Advertisement

Answer

change the initial value of phoneNumber in the useState from null to empty string and it’ll work fine. sandbox

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement