'React JS - input onChange event not setting phone number as valid until 1 extra character typed

I am using the validator package in a React application (https://www.npmjs.com/package/validator) to handle different validation examples. One I am struggling with is validator.isMobilePhone().

import React, {useState} from "react";
import validator from 'validator'

export default function Login() {

let [phone, setPhone] = useState("")
let [valid, isValid] = useState("")

const setPhoneNum = (event) => {
    setPhone(event.target.value)
    isValid(validatePhoneNumber(event.target.value))
}

const validatePhoneNumber = (event) => {
    let isValidPhoneNumber = validator.isMobilePhone(phone, "en-US")
    return (isValidPhoneNumber)
}

return (
    <>
    ...
    <input
      type="tel"
      className="w-full input-primary pl-8 focus:outline-none"
      onChange={setPhoneNum}
      value={phone}
      placeholder="123 456 7890"
    />
    ...
    <>
)
}

Login.layout = Auth

This does not return true until an extra number is typed which has to do with onChange event not setting the value of phone until a change in the input happens. I think what I need is to set the value of phone on keyDown but just cannot figure it out

15308675309 - isValidPhoneNumber - false

153086753091 - isValidPhoneNumber - true



Solution 1:[1]

Problem is here, you are passing event as arg and not used in the function.

const validatePhoneNumber = (event) => {
    let isValidPhoneNumber = validator.isMobilePhone(phone, "en-US")
    return (isValidPhoneNumber)
}

Since, you are passing the value

const validatePhoneNumber = (value) => {
    let isValidPhoneNumber = validator.isMobilePhone(value, "en-US")
    return (isValidPhoneNumber)
}

const Login = () => {
  let [phone, setPhone] = React.useState("");
  let [valid, isValid] = React.useState("");

  const setPhoneNum = (event) => {
    setPhone(event.target.value);
    isValid(validatePhoneNumber(event.target.value));
  };

  const validatePhoneNumber = (value) => {
    let isValidPhoneNumber = validator.isMobilePhone(value, "en-US");
    console.log(isValidPhoneNumber, value)
    return isValidPhoneNumber;
  };

  return (
    <input
      type="tel"
      className="w-full input-primary pl-8 focus:outline-none"
      onChange={setPhoneNum}
      value={phone}
      placeholder="123 456 7890"
    />
  );
};

const domContainer = document.querySelector('#app');
ReactDOM.render(<Login />, domContainer);
<script src="https://unpkg.com/validator@latest/validator.min.js"></script>

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"> </div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siva K V