validate country wise phone code javascript

How to Validate Country Wise Phone Code in JavaScript

When it comes to validating phone numbers, it's important to take into account the country code. JavaScript is a great tool for validating phone numbers, and there are several ways to do it.

Using Regular Expressions

One way to validate phone numbers is by using regular expressions. Regular expressions are patterns that can match certain types of strings. Here's an example:

function validatePhone(phone) {
  var regex = /^\+\d{1,3}\d{6,14}$/;
  return regex.test(phone);
}

In this example, the regular expression matches phone numbers that start with a plus sign (+), followed by one to three digits (the country code), and then six to fourteen digits (the phone number).

You can then call this function with a phone number to validate it:

var phone = "+12345678901234";
if (validatePhone(phone)) {
  console.log("Phone number is valid");
} else {
  console.log("Phone number is invalid");
}

Using an External Library

If you don't want to use regular expressions, you can use an external library like Google's libphonenumber. This library provides a comprehensive set of functions for validating and formatting phone numbers for all countries.

Here's an example of how to use libphonenumber in JavaScript:

var phoneNumber = "+12345678901234";
var phoneNumberUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
try {
  var number = phoneNumberUtil.parse(phoneNumber);
  if (phoneNumberUtil.isValidNumber(number)) {
    console.log("Phone number is valid");
  } else {
    console.log("Phone number is invalid");
  }
} catch (e) {
  console.log("Error: " + e);
}

In this example, we first create a new instance of PhoneNumberUtil from libphonenumber. We then try to parse the phone number using this object. If the phone number is valid, isValidNumber() will return true.

Conclusion

Validating phone numbers with country codes is important for ensuring accurate data and preventing errors. Whether you choose to use regular expressions or an external library like libphonenumber, there are several ways to validate phone numbers in JavaScript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe