rgExp.exec(str)
rgExp.exec(str)
exec executes a search on a string str using a Regular Expression pattern defined in an instance of a Regular Expression object rgExp, and returns an array containing the results of that search.
If the exec method does not find a match, it returns null. If it finds a match, exec returns an array. Element zero of the array contains the entire match, while elements 1 – n contain any sub matches that have occurred within the match.
rgExp.test(str)
rgExp.test(str)test returns a Boolean value (true or false) that indicates whether or not a pattern defined in the Regular Expression rgExp exists in a searched string str.
The test method returns true if the pattern exists in the string, and false otherwise.
Validation of the Format of a Phone Number
Let us say you want the respondent to specify his phone number in a particular format, allowing a digit or + as the first character and spaces between number sets, but no other characters. The following validation code uses a Regular Expression to check the formatting of the phone number, provided that the phone number is applied in an open text question with question ID phone:
var num : String = f("phone").get();
var re = /^(?:\d|\+)(?:\d| )+$/;
if(!re.test(num))
{
RaiseError();
SetQuestionErrorMessage(LangIDs.en,"Please provide your phone number, only using digits and space, and with + before your country code if it is a foreign number.");
}The Regular Expression starts the search at the beginning of the string (^). Then the first character should be either a digit or + (?:\d|\+). Because of ?: this sub expression is not stored. Then the rest of the string consists of one or more digits or spaces (?:\d| ) until the end of the string is reached ($).
In this script there are no restrictions on number of spaces or digits.
Exercise 8: Restricting the Number of Digits in a Phone Number
Based on the previous example, please modify the Regular Expression so that it checks that the phone number is on the format xxx xxx xxxx – i.e. 3 groups of 3+3+4 digits separated with space. (This time with no + for country code).
The answer is given in APPENDIX A Answers to Exercises.