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?
Similar Posts
- Validate a url using regex in Javascript
- Regex for email validation in Javascript
- Calculate square root of a number using javascript
- Check if a number is odd or even using Javascript
- Simplest Way to Find the Smallest Number in an Array using JavaScript
- Find the Third Smallest Number in an Array using Javascript
- Convert a Number or Integer to String in Javascript