Validating Phone Numbers With A Regular Expression

Posted By: Proper Noun Staff Posted On: August 17, 2021 Share:

Often times when you're looking to embed a form in your Wordpress website or WooCommerce store, you're going to be using one of 2 different plugins: Gravity Forms or Fast Secure Contact forms. FS Contact Forms is an excellent plugin, it is very customizable, and allows for you to utilize a lot of really great features, but does rely on you to provide any Regex you may need to validate your forms.

For many Wordpress website owners, this just doesn't quite cut it considering they've likely never used regex before and most of the copy/paste solutions won't be formatted for exactly what you may need. In most cases, this is really only an issue though when it comes to phone number validation, so we are going to focus on validating a phone number with regex in this post.

First thing you'll want to do is open up the form you're looking to modify, find the Phone field, and then click Show Details to view the full options for the field in question. Once you're looking at all of the available fields, you will see a field titled "Validation Regex". Put your cursor in that field and then paste in the following regular expression:

[code]
/(?([0-9]{3}))?([s .-]?)([0-9]{3})?([s .-]?)([0-9]{4})/
[/code]

Now, move your cursor in to the input that says "Regex Failed Message" and paste in: Please Enter A Valid Phone Number, or simply create a failure message of your own.

This regular expression will allow for the following number formats to be accepted

- 1234567890
- 123-456-7890
- 123 456-8900
- (123)4567890
- (123) 456 7890
- (123) 456-7890
- (123)456-7890

So how does this regular expression work? Let's break it down in to it's pieces:

- The first part ^ means the "start of the line" which will force it to account for the whole string.

- The next block (?([0-9]{3})) is saying that any 3 numbers between 0 and 9 may be used here.

- The next block ?([s .-]?) is saying that after the 3 numbers there can be either a whitespace, no whitespace, a dash, or a period.

- The next block (?([0-9]{3})) is to validate another grouping of 3 numbers between 0 and 9

- The next block ?([s .-]?) is another block that validates either a whitespace, no whitespace, a dash, or a period after the middle 3 numbers

- The final block ([0-9]{4})/ validates a grouping of four numbers between 0 and 9 and then the expression is closed with the slash.

All in all, you should be able to copy and paste the regular expression above in to your FS Contact Form fields and have no issues, but if you'd like to make any modifications or updates, the breakdown above should assist with that as well.

Proper Noun Staff

Proper Noun Staff

In-House Writing Team

Read informative articles, insights, and other resources right from the experts on the Proper Noun team.

Copyright © Proper Noun 2024