If you’re using the Sitecore Experience Forms in your project, that is excellent. If you’ve tried using the Validators to manage phone numbers you may have come across some inadequacies with the out of the box validator. Namely, that it doesn’t place any limits on the number of digits you can enter.
Fear not!
Here is a quick tutorial on how to replace the out of the box value with a helpful Regex that should give you more mileage for all US and Canada phone numbers.
Regex: ^(\d{1}-?\(?\d{3}\)?-? *\d{3}-? *-?\d{4}$)|^(\(?\d{3}\)?-? *\d{3}-? *-?\d{4}$)
Here is a small range of formats this will support and restrict validation to:
- 12223334455
- 2223334455
- 1-222-333-4455
- 1222-333-4455
- 1(222)-333-4455
- 1 222 333 4455
If you want to extend this for other international formats, you can easily append another capture group |^(..$).
The point of this regex is to limit the allowed characters to dashes and spaces. It will allow your visitor some flexibility when entering in data, but prevent them from adding anything particularly undesired. This should be a great place to start to get the most out of your validator, while still filtering out unwanted characters and ‘playing-nice’ with auto-format techniques that many front-end professionals tend to employ in web applications.
I hope this tutorial was helpful. Be sure to check out our other Sitecore practice blogs for more tips and tricks.