Sorry, a Regex question


(Eric Stephan) #1

Hello all – Can someone help me with a fairly simple Regex question? I have tried a few times to become conversant in Regex but never succeeded.

I have a text question in a commcare form…

and I am hoping to add validation so that it will ONLY allow the submission if:

  • the text that is entered is in fact a valid integer of any length… like 235, 29,1, 39587
    OR
  • the text that is entered is this exact three-character string: <50

… Note, I think you are likely noticing that this is a pretty clunky, ungraceful UI. Believe me, I know. but it’s the result of a discussion and my team is pretty sure they want this.

Can you tell me what I would put in the validation field to allow just what I wrote above? thanks much… Perhaps this will serve as a formative tutorial for me.

Eric


(Ethan Soergel) #2

Hi Eric, here’s a regular expression which should do what you describe. I find it helpful to use an online regular expression tester (like this one) when writing these.

^(<50|[0-9]+)$

You might also consider adding a question which says “is the value less than 50?”, and only display the integer question if it isn’t. You could then use a hidden value to combine the results of these two questions into whatever format you need, such as the string “<50” or an integer value.

Assuming you do want this in one text box, you might have more flexibility if you use an “or” statement rather than a single regex. For instance, to meet the above conditions and validate that if an integer is entered, it must be greater than or equal to 50, you could use an expression such as:

VALUE = “<50” or regex(VALUE, “^[0-9]+$”) and int(VALUE) >= 50


(Eric Stephan) #3

Hello Ethan – this is truly great. Thanks much!!! Note, I have definitely been telling the team that a second question would make this all cleaner (and avoid the user having to fiddle with the Qwerty keyboard, etc.) Your note gave me the energy to tell them how nuts it would be otherwise. again, thanks! if I get tripped up on the above, I’ll reply again. Thanks --eric