javascript

Using regex to validate a phone number in Javascript

Validating phone numbers is an important part of any web form. There are many ways to do this, but one of the most effective is to use a regular expression, or "regex." Regex can be used to validate a wide variety of data, including phone numbers. Here, we'll show you how to use regex to validate a phone number in Javascript. We'll also provide a few tips on how to make sure your phone number regex is as effective as possible.

function is_number_valid(val) {
    const re = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
    return re.test(val);
}

console.log("01234567890: " + is_number_valid("01234567890")); // true
console.log("123-456-7890: " + is_number_valid("123-456-7890")); // true
console.log("123.456.7890: " + is_number_valid("123.456.7890")); // true
console.log("123 456 7890: " + is_number_valid("123 456 7890")); // true
console.log("(123) 456 7890: " + is_number_valid("(123) 456 7890")); // true
console.log("1: " + is_number_valid("1")); // false
Was this helpful?