Home >Web Front-end >JS Tutorial >How can I validate phone numbers with multiple formats (e.g., (123) 456-7890, 123-456-7890, and 1234567890) using JavaScript?
Validating Phone Numbers with Multiple Formats Using JavaScript
The given regular expression validates phone numbers in two formats: (123) 456-7890 and 123-456-7890. However, we can enhance its functionality to include the additional format of ten consecutive numbers, i.e., 1234567890.
To accomplish this, we modify the regular expression as follows:
/^[\+]?[0-9]{0,3}\W?+[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
Let's break down the expression:
This enhanced regular expression validates the following formats:
(123) 456-7890 (123)456-7890 123-456-7890 123.456.7890 1234567890 +31636363634 075-63546725 +1 (415)-555-1212 +1 (123) 456-7890 +1 (123)456-7890 +1 123-456-7890 +1 123.456.7890 +1 1234567890 +1 075-63546725 +12 (415)-555-1212 +12 (123) 456-7890 +12 (123)456-7890 +12 123-456-7890 +12 123.456.7890 +12 1234567890 +123 075-63546725 +123 (415)-555-1212 +123 (123) 456-7890 +123 (123)456-7890 +123 123-456-7890 +123 123.456.7890 +123 1234567890 +123 075-63546725 +1(415)-555-1212 +1(123) 456-7890 +1(123)456-7890 +1123-456-7890 +1123.456.7890 +11234567890 +1075-63546725 +12(415)-555-1212 +12(123) 456-7890 +12(123)456-7890 +12123-456-7890 +12123.456.7890 +121234567890 +123075-63546725 +123(415)-555-1212 +123(123) 456-7890 +123(123)456-7890 +123123-456-7890 +123123.456.7890 +1231234567890 +123075-63546725
The above is the detailed content of How can I validate phone numbers with multiple formats (e.g., (123) 456-7890, 123-456-7890, and 1234567890) using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!