How to Validate Mobile Number Length in ReactJS?


Nowadays, validation of mobile number input is a required feature for any application, and it requires validation of the length of the mobile number.

Many apps use the mobile number for authentication purposes, sending OTP to users' mobile numbers for successful authentication. If the user enters the wrong mobile number, the app can face issues with sending OTP.

So, before the user submits the mobile number for registration or authenticates the app, our app should validate the length of the mobile number.

This tutorial will teach us various approaches to validating a mobile number using ReactJs.

Before we start, users need to set up the React project.

Check the length of the user’s input

In this approach, we will validate the input’s length. Whenever the input value changes, we will check that if the input length is equal to 10, we can hide the error message. If the length of the input is not equal to 10, we can show the error message for validating the input.

Syntax

Users can follow the syntax below to validate the phone number’s length using the length property.

if (new_Number_length > 10 || new_Number_length < 10) {
   setShowError(true);
} else if (new_Number_length == 10) {
   setShowError(false);
}

In the above syntax, we set true to show an error message when a user enters a phone number of less or greater than the length of 10.

Example

In the example below, we have created the number input. Also, we invoke the handlePhoneNumber() function whenever the input value changes.

In the handlePhoneNumber() function, we get the latest input value using the event and length of the input using the length property. Furthermore, we used the setPhoneNumber() function to set the latest value to the phoneNumber.

Next, we validate the length of the phone number using the if-else statement and setting up a true or false value to the showError variable according to the length of the phone number.

import React, { useState } from "react";

const App = () => {
  const [phoneNumber, setPhoneNumber] = useState("0123456789");
  const [showError, setShowError] = useState(false);
  function handlePhoneNumber(event) {
    let new_Number = event.target.value;
    let new_Number_length = new_Number.length;
    setPhoneNumber(new_Number);

    if (new_Number_length > 10 || new_Number_length < 10) {
      setShowError(true);
    } else if (new_Number_length == 10) {
      setShowError(false);
    }
  }
  return (
    <div>
      <h2> Validate the length of the mobile number using ReactJS </h2>
      {showError ? (
        <div style = {{ color: "red" }}> Invalid Mobile Number Length </div>
      ) : (
        <div> Valid Mobile number. </div>
      )}
      <input type = "number" value = {phoneNumber} onChange={handlePhoneNumber} />

      <div> The phone number is +91 {phoneNumber} </div>
    </div>
  );
};

export default App;

Output

Use the Regular Expression

We can use the regular expression to validate any string. We can use the match() method to validate the string by matching it with any regular expression.

We will create a regular expression that matches for digits in the string, and the string’s length is equal to 10.

Syntax

Users can follow the syntax below to use regular expressions to validate the length of the phone number.

if (!new_Number.match("^[0-9]{10}$")) {
   // show error
} else {
   // hide error
}

In the above syntax, [0-9] represents the digits only, and {10} represents the string length. The ‘$’ represents the string length from the end.

Example

In the example below, we take the phone number input from users as we have done in the first example. We validate the input value using regular expressions whenever the user changes the input.

According to the boolean result from the match() method, we set the error message to show.

import React, { useState } from "react";

const App = () => {
  const [phoneNumber, setPhoneNumber] = useState("0123456789");
  const [errorMessage, setErrorMessage] = useState(
    "Your phone number is not valid!"
  );
  function handlePhoneNumber(event) {
    let new_Number = event.target.value;
    setPhoneNumber(new_Number);
    // Match phone number with a regular expression to check if the length is 10 digits.
    if (!new_Number.match("^[0-9]{10}$")) {
      setErrorMessage("Your phone number is not valid!");
    } else {
      setErrorMessage("Phone Number is valid!");
    }
  }
  return (
    <div>
      <h2>
        {" "}
        Validate the length of the mobile number using{" "}
        <i> Regular expression </i> in ReactJS.{" "}
      </h2>
      <div> {errorMessage} </div>
      <input
        type = "number"
        value = {phoneNumber}
        onChange = {handlePhoneNumber}
        maxLength = "10"
      />
      <div> The phone number is +91 {phoneNumber} </div>
    </div>
  );
};

export default App;

Output

We learned to validate the length of the phone number input in this tutorial. The best way to validate the mobile number’s length is using a regular expression, as it also validates the mobile number.

Updated on: 08-Sep-2023

701 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements