Forms-Regex

Sometimes data has to follow a certain form, but you can't list all the possible valid values. In that case you can specify that the entered value must match a "regular expression". Regular expressions (RE) are extremely powerful tools and it is entirely beyond the scope of this page to explain the syntax of the actual RE, but we can give several examples.

As previously, only "the interesting part" will be shown here. See Forms-RequiredFields for the part of the page/form that comes before and after.

1. There are times you want to specify that a value must be numeric:

(... stuff before the interesting stuff)
if test "${num}" ~= "^[0-9]+$"
then
   echo "%green%Great, you know what a number is.%%"
else
   echo "%red%Oops! Only numbers.  Why don't you try again?%%"
fi
(stuff after the interesting stuff ...)

1a. Previously on Forms-RangeValues we showed how to do a range of numeric values. However, if the user entered "Sam" then we got an ugly error message. Now we can first ensure that the value is numeric and after that we can ensure that it falls within the range:

(... stuff before the interesting stuff)
if test "${num}" ~= "^[0-9]+$" && test "${num}" -ge 1 && test "${num}" -le 10
then
   echo "%green%Great, I love that number!%%"
else
   echo "%red%Oops! Only numbers and they must be between 1 and 10.  Why don't you try again?%%"
fi
(stuff after the interesting stuff ...)

1b. Same problem, but let's separate the validation to give more informative error messages

(... stuff before the interesting stuff)
set errs = 0
if ! test "${num}" ~= "^[0-9]+$"
then
   echo "%red%Oops! Only numbers!%%"
   set errs ++
fi
if test "${num}" -lt 1
then
   echo "%red%Oops! Your number is too small.  Try again%%"
   set errs ++
fi
if test "${num}" -gt 10
then
   echo "%red%Oops! Your number is too big.  Try again%%"
   set errs ++
fi
if test ${errs} -gt 0
then
   echo "%red%Due to the errors above the information you entered was not saved.%%"
   exit # Don't go on
fi
(stuff after the interesting stuff ... probably saving some data?)

2. Let's make sure that their name has a first and a last name, each capitalized. And YOU can explain to the McCalls and MacElwains of this world why their name doesn't fit...

(... stuff before the interesting stuff)
if test "${name}" ~= "^[A-Z][a-z]* [A-Z][a-z]*$"
then
   echo "%green%Welcome, ${name}.%%"
else
   echo "%red%Your name doesn't match what I think a name should look like try again.%%"
fi
(stuff after the interesting stuff ...)

Regular expressions are a very powerful way to validate data. But you have to be as careful when crafting your RE as you are when you are writing a program -- lots of careful testing...