Regex validation – how to check for exactly 4 digits in Commcare integer field

commcare

I'm using regex as validation, to check that year (integer field) entered is exactly 4 digits. My expression regex(., '[0-9]{4}') isn't working in Commcare, but when I checked at http://www.regexr.com/, [0-9]{4} does work. What am I missing in my Commcare function?

Best Answer

There are a couple of issues here.

Regexes are typically only used for string fields inside CommCare ("Text", "Phone number or Numeric ID", hidden variables, etc). If you want to do a validation on the "Integer" field, it's better to use numerical constraints. The way I would do this is:

. >= 1000 and . <= 9999

If you want to allow your 4-digit number to start with a 0, you should use the "Phone number or Numeric ID" data type. (Integers can't start with zeroes). Then, your regex will almost work.

Currently, this matches any string that contains a sequence of 4 digits anywhere in the string. If you want to match only strings that contain EXACTLY 4 digits, you'll need to add the ^ (start of string) and $ (end of string) characters. So the full expression would be:

regex(., '^[0-9]{4}$')

Happy matching!