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.

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.

Here is an example response for a valid number:

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.

Frequently Asked Questions

What is phone number validation in Yup?

Phone number validation in Yup means adding a rule to a Yup schema that checks whether a submitted string matches a valid phone number format before the form is submitted. Yup offers several ways to do this: a regex pattern with .matches(), a custom .test() function backed by libphonenumber-js, or a third-party plugin like yup-phone. Each approach runs synchronously on the client side and catches formatting errors early.

Should I use a regex or libphonenumber-js with Yup?

Regex is simpler and adds no dependencies, making it a good fit when you only need to enforce a single format like E.164. libphonenumber-js is more reliable for international and national number formats because it uses Google's phone metadata and handles edge cases that a hand-written regex often misses. The trade-off is bundle size: libphonenumber-js adds roughly 145 kB, while a regex adds nothing. For forms that accept numbers from multiple countries, libphonenumber-js is the safer choice.

What does the yup-phone plugin add over plain Yup?

The yup-phone plugin extends Yup's string type with a .phone() method, so you can write Yup.string().phone('US', true) instead of wiring up a custom .test() manually. It supports strict and loose validation modes and accepts an optional country code for region-specific rules. One known issue is that yup-phone can behave unexpectedly with nullable fields, so you may need to chain .nullable() carefully or switch to yup-phone-lite, which uses libphonenumber-js and has a smaller footprint.

How do I validate a phone number conditionally in Yup?

Use Yup's .when() method to tie phone validation to another field in the same schema. For example, you can require a phone number only when a user selects SMS as their contact preference, and skip validation entirely otherwise. This keeps the schema in sync with form state without requiring manual imperative checks outside of Yup.

Can Yup tell me if a phone number is actually active or reachable?

No. Yup performs syntactic validation only: it checks whether a string looks like a valid phone number, not whether the number is assigned, active, or reachable. To verify that a number is real and reachable, you need a server-side API like Abstract's Phone Validation API, which queries live telecom data across 190+ countries and returns carrier, line type, and active status. The recommended pattern is to do a lightweight format check with Yup on the client, then confirm the number server-side before storing it.

How do I combine Yup validation with Abstract's Phone Validation API?

First validate the phone number's format on the client using a Yup schema with .matches() or a libphonenumber-js .test(). Once the format check passes, send the number to Abstract's Phone Validation API from your server or a serverless function so the API key is never exposed in the browser. The API returns a JSON response with fields like valid, line_type, carrier, and country. You can then surface a server-side error to the user if the number is flagged as invalid or unassigned.

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