-1

I am writing a function which checks the input value.

const [input, setInput] = useState("")

<input type="text" value={input} onBlur={handleCheckValue} onChange={(e) => setInput(e.target.value)} />

And the problem is I don't know how to write check function. I want a valid string with represent a number like "12345" "489796" ...etc

  const handleCheckValue = () => {
    setIsValid(false);
    if (input === undefined || input === null || input.trim() === "" || isNaN(input)){
      setWarnText(warnTextMap["notValid"]);
    } else {
      setIsValid(true);
    }
  };

Should I check if it is undefined or null? I googled and searched but can't find an question like this..

Luna
  • 23
  • 4

2 Answers2

1

As I understand you want to have only numbers in your input.

In this case you can change your input type to be number:

<input type="number" value={input} onBlur={handleCheckValue} onChange={(e) => setInput(e.target.value)} />
1

By specification value is always a string. Check the reference guide with types and details for all properties of the input elements: https://www.w3schools.com/tags/tag_input.asp

value   text    Specifies the value of an <input> element

If you want to understand if the value is a valid number you should use: !isNaN(parseInt(value)). This is going to tell you true in cases where the string is a valid number and false in all other cases.

Martin Chaov
  • 824
  • 7
  • 17