Sometimes an expected text response needs to conform to existing rules, e.g. a beneficiary ID number such as "adtqr" that had previously been assigned by the program prior to distribution. KoBo allows restricting possible responses to text questions (and technically any other question) by using the very powerful regular expression syntax, or regex.

To use a regex to restrict possible options, follow these steps for your text question:

  1. Go to the question's Settings
  2. Go to Validation Criteria, choose the manual syntax option
  3. Enter your regex between the quotation marks of this formula regex(., " ")

For reference, "." (the period) refers to 'this question', while the regular expression inside the quotation marks needs to conform to the established regex rules. To build your regular expression see http://www.regexr.com for help and examples.

Examples

Below is an example of how to restrict text entry to exactly five lowercase letters (e.g. abcde) using the code regex(.,'^([a-z]){5}$'):

Other examples:

  • Only allow a number of nine digits (e.g. a phone number): regex(.,'^[0-9]{9}$')
  • For a ten digit phone number use regex(.,'^[0-9]{10}$')
  • If the first number can’t be 0, use regex(.,'^[1-9][0-9]{8}$')
  • Only allow a valid email address regex(., '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}')
  • Enter a code (e.g. beneficiary ID) consisting of numbers and lowercase letters, up to 6 characters long regex(., '^[a-z]{1,6}$')
  • Enter a beneficiary ID corresponding to a specific existing format, e.g. "mz-00-0000" regex(.,'^mz-[0-9]{2}-[0-9]{4}$') (see screenshot below)
Did this answer your question?