Looking to collect US phone numbers and validate that the entries are correct? Here's how!
- Click Question at the bottom of the page where you wish to add your phone number question.
- Select Textbox from the Question Type dropdown menu and enter your question text.
- Next, head over the Validation tab and select RegEx in the Answer Format dropdown menu.
- In the Common RegEx Patterns dropdown menu that appears after selecting Regex, select US Phone Number. This will populate with the RegEx pattern that will validate for a 7 or 10-digit phone number separated using either dashes/hyphens or spaces.
- Finally, enter the message you wish to display if the survey respondent's entry does not pass your RegEx validation rules.
Optional Customization: Automatically Add Hyphens
The US Phone Number RegEx validation requires a 7 or 10-digit phone number separated using either dashes or spaces. If you want to ensure that dashes/hyphens are added to the phone number, we have a piece of JavaScript that will automatically add these, if the respondent doesn't.
To add the JavaScript, follow these steps:
- Edit the question that is capturing your phone number and navigate to the Layout tab.
- In the CSS Class Name field, add the word
phone
and Save your question. - On the same survey page as your phone question, add a JavaScript Action and paste the below JavaScript code into the action:
$( document ).ready(function() { $('.phone input').on('input', function() { var number = $(this).val().replace(/[^\d]/g, '') if (number.length == 7) { number = number.replace(/(\d{3})(\d{4})/, "$1-$2"); } else if (number.length == 10) { number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"); } $(this).val(number) }); });
- Save the JavaScript Action and test your survey to see it in action.
If a respondent enters a 10-digit phone number as 123 123 1234
, it will be converted to (123) 123-1234
. If a respondent enters a 7-digit number as 123 1234
, it will be converted to 123-1234
.