0
0
JavascriptHow-ToBeginner · 3 min read

How to Validate Phone Number Using JavaScript: Simple Guide

To validate a phone number in JavaScript, use a regular expression (RegExp) that matches the desired phone number format. You can test the input string with RegExp.test() to check if it is valid.
📐

Syntax

Use the RegExp.test(string) method to check if a phone number matches a pattern.

  • RegExp: A regular expression defining the phone number format.
  • string: The phone number input to validate.
  • test(): Returns true if the string matches the pattern, otherwise false.
javascript
const phonePattern = /^\+?\d{10,15}$/;
const isValid = phonePattern.test('+12345678901');
💻

Example

This example shows how to validate a phone number that may start with a plus sign and contains 10 to 15 digits.

javascript
function validatePhoneNumber(phone) {
  const phonePattern = /^\+?\d{10,15}$/;
  return phonePattern.test(phone);
}

console.log(validatePhoneNumber('+12345678901')); // true
console.log(validatePhoneNumber('1234567890'));   // true
console.log(validatePhoneNumber('123-456-7890')); // false
console.log(validatePhoneNumber('phone12345'));   // false
Output
true true false false
⚠️

Common Pitfalls

Common mistakes include:

  • Not accounting for different phone formats like spaces, dashes, or parentheses.
  • Using too strict or too loose regular expressions.
  • Ignoring international formats or country codes.

Always define the expected format clearly before writing your validation.

javascript
/* Wrong way: allows letters and symbols */
const wrongPattern = /^\w+$/;
console.log(wrongPattern.test('123-456-7890')); // false (incorrect)

/* Right way: strict digits with optional plus */
const rightPattern = /^\+?\d{10,15}$/;
console.log(rightPattern.test('123-456-7890')); // false (correct)
Output
false false
📊

Quick Reference

PatternDescriptionExample Matches
^\+?\d{10,15}$Optional plus, 10-15 digits+12345678901, 1234567890
^\d{3}-\d{3}-\d{4}$US format with dashes123-456-7890
^\(\d{3}\) \d{3}-\d{4}$US format with parentheses(123) 456-7890
^[0-9]{10}$Exactly 10 digits1234567890

Key Takeaways

Use regular expressions with RegExp.test() to validate phone numbers in JavaScript.
Define the phone number format clearly before writing your validation pattern.
Avoid overly loose patterns that allow invalid characters like letters or symbols.
Consider international formats and optional plus signs for country codes.
Test your validation with various valid and invalid phone number examples.