Have an idea?

Visit Sawtooth Software Feedback to share your ideas on how we can improve our products.

Postcode verification

I am using a regular expression to verify my 4 digit postcode at Q1.
var regex = /^\d{1,4}$/;
var answer = SSI_GetValue("Q1");
if(regex.test(answer)) { 
}
else {
  strErrorMessage="Please revise your answer and enter a 4 digit postcode."; 
}

This works fine.

My problem is this question is non-compulsory. So when someone answers the question, the verification code ensures the respondent enters a 4 digit postcode. When they decide not to answer the question, the verification code still runs and won't let the respondent proceed.

Looking for a tweak to the above code to cater for the non-answering respondent.
asked Jul 11, 2016 by Paul Moon Platinum (98,670 points)
P.S.: This is starting to sound like a numeric question with a min of 1000 and a max of 9999.  Perhaps there's a reason why a numeric won't work in this situation -- I'm just throwing this out there.
I'm fine either way - as long as it verifies the response correctly.

1 Answer

+2 votes
You just need to update your 'if' statement to catch blank answers as well as answers that fit the regex:

if(regex.test(answer) || answer == '') {
answered Jul 11, 2016 by Zachary Platinum Sawtooth Software, Inc. (205,875 points)
Thanks Zachary. I still have a problem however?

This question is setup as an O/E question to enable the regular expression to work. I have it setup as non-compulsory. It appears having it setup as non-compulsory throws the verification out. Your solution made sense but it still doesn't work?

If I have it set to compulsory, my initial script works a treat.

Check it out with a compulsory versus a non-compulsory setup.

Any suggestions?
I don't think I'm seeing your problem on my end.  When I disabled require response, I'm able to submit answers like "1234", "5", and the empty response and I am unable to submit answers like "12345" or "abc".  This is the intended behavior from my understanding.

Could you double-check that your line 3 looks just like my line of code, no mismatched parenthesis or anything?
If I do not enter a response, it allows me to proceed. That's OK.

If I enter "1234". That's OK

If I enter any letters, it prevents me from proceeding. That's OK.

But If I enter less than a 4 digit numeric response ("1" or "12" or "123"), that's where I get the problem. This is the combination that proceeds when it should not.
I see, that's the regex stirring up trouble.  In regular expressions, "{x, y}" requires that the requirement before it be repeated at least "x" times and at most "y" times.  Because you want digit requirement repeated exactly four times, you should use:

/^\d{4}$/
Thanks Zachary. Works a treat now. Much appreciated.
...