Guides
Last updated
July 20, 2025

5 Ways to Implement Phone Number Validation in Yup

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
phone validation
 API key now
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Validating phone numbers in Yup is key for clean user data. We'll explore five ways to implement this, complete with code snippets. You'll see the pitfalls of common client-side methods and how Abstract API offers a more reliable approach for robust, server-backed validation without the usual drawbacks.

How to Implement Phone Number Validation in Yup

Here are four common methods to validate phone numbers with Yup. Each approach has a different implementation, from simple regular expressions to more complex, context-aware rules for dynamic forms.

Regex with the .matches Method

This method uses a single regular expression with Yup’s built-in “.matches” function. It is a direct way to check a phone number’s format, and the validation runs synchronously without extra dependencies.

The pattern should align with the E.164 standard to avoid country-specific rules. The code defines a schema where a phone number is a required string. The “.matches” function then tests the input against a regex pattern that checks for an optional plus sign followed by 9 to 14 digits.

import * as Yup from 'yup';

const phoneSchema = Yup.string()
  .required('phone required')
  .matches(/^\+?[1-9]\d{9,14}$/, 'invalid phone');

A Custom .test with libphonenumber-js

This approach uses the “libphonenumber-js” library, which contains the same metadata Google uses. You can delegate complex validation logic to this library through Yup’s custom “.test” function.

This method avoids regex drift and handles national versus international formats. The code imports the “isValidPhoneNumber” function and creates a Yup string schema. A custom test named “is-valid-e164” then uses this function to validate the number.

import { isValidPhoneNumber } from 'libphonenumber-js';
import * as Yup from 'yup';

const phoneSchema = Yup.string().test(
  'is-valid-e164',
  'invalid phone',
  value => isValidPhoneNumber(value || '')
);

An External addMethod Plugin

Packages like yup-phone extend Yup’s functionality by adding a “.phone()” method. There is also a yup-phone-lite version. These packages use Yup’s “addMethod” feature to create a more readable schema.

They offer features like strict and loose validation modes and can automatically default to a specific country. The code shows how to import the plugin and use it with different configurations, such as a country-specific check or a custom error message.

import * as Yup from 'yup';
import 'yup-phone';           // or 'yup-phone-lite'

const usSchema    = Yup.string().phone().required();          // defaults to US
const inStrict    = Yup.string().phone('IN', true).required();
const customError = Yup.string().phone('US', false, '${path} bad').required();

Context-Aware .when Rules

Yup’s “.when” conditional validation allows you to link the phone number rule to another field, like a country selector. This enables you to change validation patterns or plugins dynamically based on user input.

This approach is useful for applications that support multiple regions within a single code bundle. The code creates a schema where the phone validation rule changes based on the selected country. If the country is “US,” it uses a specific regex, otherwise, it falls back to a different validation test.

const schema = Yup.object({
  country: Yup.string().required(),
  phone:   Yup.string().when('country', {
    is:  'US',
    then: Yup.string().matches(/^\+1\d{10}$/, 'US phone invalid'),
    otherwise: Yup.string().test(
      'intl',
      'intl phone invalid',
      v => isValidPhoneNumber(v || '')
    )
  })
});

Challenges of Phone Number Validation in Yup

These client-side methods seem convenient but introduce significant reliability and security risks. The validation logic often contains subtle flaws that compromise data quality and expose applications to potential fraud.

  • Numbering plans change often. Methods like yup-phone or a custom test with libphonenumber-js rely on bundled metadata. If this data is outdated, the validation fails for real numbers and allows fake ones.
  • The yup-phone plugin conflicts with Yup's nullable contract. It flags empty values as errors, which forces developers to add extra .when or .test logic. This workaround increases maintenance and introduces hidden edge cases.
  • These methods only perform syntactic checks. A library like libphonenumber-js cannot confirm if a number is active or reachable. A correctly formatted number might still be fake, which prevents guaranteed SMS delivery.
  • All these validation methods run on the client side. A user can disable JavaScript or modify the schema to bypass checks. Without server-side duplication, your API might accept unvalidated data, which opens fraud vectors.

Validate Phone Numbers with Abstract API
Implement phone number validation in Yup to stop bad data and collect accurate user information.
Get started for free

How Abstract API Handles Phone Number Validation in Yup

Abstract API addresses the core weaknesses of traditional validation methods. It moves beyond simple syntax checks to provide semantic validation against real-time telecom data.

  • It consults a real-time telecom dataset that covers more than 190 countries to verify numbers.
  • It returns a boolean flag that confirms if a number is active and reachable.
  • It provides useful metadata, such as the line type, carrier, and location details.
  • It moves the complex validation logic out of the browser, which keeps the client bundle small.

How to Bring Abstract API to Your Dev Environment

Once you are familiar with Abstract’s capabilities, to add its phone number validation API to your project is simple.

  • Create a free account on Abstract to get your Phone Validation API key.
  • Place the key in a .env file with the variable name ABSTRACT_API_KEY.
  • Install the necessary packages to make HTTP requests and load environment variables.
npm i axios dotenv

Sample Phone Number Validation Implementation with Abstract API

The helper function below shows a complete validation flow. It first uses a Yup schema for a quick format check on the client side. Then, it sends the phone number to the Abstract API endpoint.

If the API response property "valid" is not "true", the function throws an error. Otherwise, it returns the full JSON object from the API, which contains rich metadata about the number.

import axios from 'axios';
import * as Yup from 'yup';

const phoneSchema = Yup.string()
  .required('phone required')
  .matches(/^\+?[1-9]\d{9,14}$/, 'bad format');

export async function validatePhone(value) {
  await phoneSchema.validate(value);              // fast client check
  const { data } = await axios.get(
    'https://phonevalidation.abstractapi.com/v1/',
    { params: { api_key: process.env.ABSTRACT_API_KEY, phone: value } }
  );
  if (!data.valid) throw new Error('unreachable phone');
  return data;                                    // contains carrier, region, etc.
}

Here is an example response for a valid number:

{
  "phone": "14152007986",
  "valid": true,
  "format": { "international": "+14152007986", "local": "(415) 200-7986" },
  "country": { "code": "US", "name": "United States", "prefix": "+1" },
  "location": "California",
  "type": "mobile",
  "carrier": "T-Mobile USA, Inc."
}

The "valid" field confirms the number is active. The "format" object provides normalized versions for display or storage. The "country", "location", "type", and "carrier" fields offer detailed context that helps with regional logic and route decisions.

Final Thoughts

Traditional validation methods only check syntax. They cannot confirm if a number is active or identify its line type, which leaves gaps for fraud and affects SMS deliverability.

Abstract API solves this with real-time data for semantic checks. Consider an account on Abstract API to get your free API key and reliably validate user phone numbers.

Validate Phone Numbers with Abstract API
Validate phone numbers in your Yup forms to maintain clean data and reliable user contact info.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required