3

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?

3 Answers 3

6

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!

2

That regex should work, but it will only work on question types that store string values.

Because the question type stores an integer, regex won't work. But to validate a 4-digit value for an integer question, you could also use this expression:

. >= 1000 and . <= 9999

Also, as an aside, you can substitute \d for [0-9] in regular expressions. So if you had a string question that you wanted to validate exactly 4 digits with, you could use: regex(., '^\d{4}$')

1

Perhaps CommCare doesn't support the {n} notation? (Not all regex implementations are the same). You could try [0-9][0-9][0-9][0-9] as an alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.