What is Yup?
Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existing value, or both. Yup is commonly used for form validation in React and other JavaScript frameworks.
Key Features of Yup:
- Schema-based validation: Define complex validation logic using intuitive schemas.
- Type coercion: Automatically convert values to the correct type.
- Asynchronous validation: Useful for async operations like checking username availability.
- Custom validation rules: Add your own validation logic tailored to your app's needs.
Commonly used with form libraries like React Hook Form or Formik, Yup offers:
- Schema-based validation: Structure your form data clearly.
- Type coercion: Automatically convert values to the correct type.
- Asynchronous validation: Validate fields asynchronously (e.g., via API).
- Custom validation rules: Build reusable logic for specific needs.
Why Use Yup for Phone Number Validation?
Validating phone numbers on the client side offers several key advantages:
- Improved User Experience: Users receive instant feedback on invalid input.
- Reduced Server Load: Catch basic formatting errors before data is sent.
- Simplified Form Handling: Centralized validation logic using schemas.
- Code Reusability: Reuse validation logic across multiple forms.
Basic Phone Number Validation with Yup
Let’s walk through a few basic examples of using Yup to validate phone number fields:
1. Required and String Type
import * as Yup from 'yup';
const phoneSchema = Yup.string()
.required('Phone number is required')
.typeError('Phone number must be a string');
2. Length Validation
const phoneSchema = Yup.string()
.required('Phone number is required')
.min(10, 'Phone number must be at least 10 digits')
.max(15, 'Phone number must be no more than 15 digits');
These simple rules ensure the field is filled out correctly before submission.
Advanced Phone Number Validation with Yup
Now let’s dive into more advanced validation scenarios.
1. Regex Validation
const phoneSchema = Yup.string()
.matches(/^\+?[1-9]\d{9,14}$/, 'Enter a valid phone number');
This regex allows optional + and ensures a valid number format according to E.164 standards.
2. Custom Validation Function
const phoneSchema = Yup.string().test(
'is-valid-phone',
'Invalid phone number format',
value => value && value.replace(/\D/g, '').length >= 10
);
3. International Phone Number Validation (with libphonenumber-js)
import { isValidPhoneNumber } from 'libphonenumber-js';
const phoneSchema = Yup.string().test(
'is-valid-international-phone',
'Invalid international phone number',
value => isValidPhoneNumber(value || '')
);
4. Conditional Validation
const schema = Yup.object({
country: Yup.string().required(),
phone: Yup.string().when('country', {
is: 'US',
then: Yup.string().matches(/^\+1\d{10}$/, 'Invalid US phone number'),
otherwise: Yup.string().required('Phone number is required'),
}),
});
These strategies let you customize validation based on input context.
Limitations of Client-Side Validation with Yup
While Yup offers a smooth and powerful solution for client-side validation, it comes with certain limitations that developers should be aware of when building robust, production-level applications:
1. Bypassable by Malicious Users
- Client-side validation happens entirely in the user's browser. This means that savvy users or attackers can easily manipulate the form, disable JavaScript, or edit the validation logic using browser developer tools. If your application relies solely on Yup for validation, it becomes vulnerable to data tampering and injection of invalid or harmful information. This is why client-side validation should never be your only line of defense.
2. Dependent on JavaScript Availability
- Because Yup is a JavaScript-based library, it requires JavaScript to be enabled in the browser. If a user disables JavaScript (intentionally or unintentionally), none of the validation logic will run. This could lead to forms being submitted with completely unvalidated or malformed data. While most modern users have JavaScript enabled, accessibility and edge-case scenarios still require a fallback or additional server-side checks.
3. Can’t Guarantee Data Accuracy
- Even if the format of the phone number is correct, Yup can’t tell you whether the number is real, reachable, or assigned to a user. For example, a string like +1234567890 might pass all formatting checks but still be a nonexistent or fake number. Without external verification, Yup is limited to syntactic validation—it doesn’t offer semantic validation or real-world accuracy.
4. Lacks Metadata and Contextual Information
- Yup doesn’t provide any additional context about the phone number, such as:
- The country or region it's associated with
- The carrier (e.g., AT&T, T-Mobile)
- Whether it's a mobile, landline, or VOIP number
- If it's a temporary or disposable number
This type of data is crucial for businesses looking to prevent fraud, tailor experiences by region, or verify user authenticity. Since Yup runs entirely in the browser, it doesn’t have access to external databases or APIs to provide this level of detail.
AbstractAPI’s Phone Validation API: Complementing Yup
To overcome client-side limitations, pair Yup with a server-side verification tool like AbstractAPI’s Phone Validation API.
Why Use AbstractAPI?
- Real-Time Validation: Check if a number is active and correctly formatted.
- Detailed Data: Get country, carrier, and line type.
- Fraud Detection: Spot fake or disposable numbers.
- Compliance: Ensure compliance with data and privacy regulations.
Example: Server-Side Verification with AbstractAPI
async function verifyPhoneWithAPI(phone) {
const response = await fetch(`https://phonevalidation.abstractapi.com/v1/?api_key=YOUR_API_KEY&phone=${phone}`);
const data = await response.json();
if (!data.valid) {
throw new Error('Phone number is not valid');
}
return data;
}
Use this check after Yup validation on the client side, for robust data accuracy.
Benefits of AbstractAPI:
- Real-Time Validation: Confirms if numbers are active.
- Carrier & Location Info: Extra metadata like line type.
- Fraud Prevention: Identify fake or disposable numbers.
- Regulatory Compliance: Helps with GDPR and telecom compliance.
Other Code Example
async function verifyPhoneServerSide(phoneNumber) {
const response = await fetch(`https://phonevalidation.abstractapi.com/v1/?api_key=your_api_key&phone=${phoneNumber}`);
const data = await response.json();
console.log(data);
}
Use this after client-side validation to add a second layer of accuracy.
Best Practices for Phone Number Validation with Yup and AbstractAPI
To maximize reliability and performance:

- Use Yup for client-side validation to improve UX and reduce server load.
- Use AbstractAPI for accurate, real-time server-side checks.
- Display clear error messages to help users correct input.
- Regularly update regex rules and phone formats.
- Use metadata from AbstractAPI to make informed decisions.
Conclusion: Combine the Best of Both Worlds
By combining the power of Yup for client-side validation with AbstractAPI’s robust server-side verification, you can build a complete phone number validation system. This approach improves UX, boosts data accuracy, and protects your business.
Learn More
Explore AbstractAPI’s Phone Validation API documentation for full capabilities and integration guides.