Join the Discussion
Sometimes you have a situation where a text field must contain two specific characters somewhere in the text string and although they don't have to appear in set positions, one of those characters must precede the other. We need to be able to test that the characters appear in the required order. Th following function shows how to achieve this:
var pos1 = parmField.indexOf(first,0);
if (pos1 == -1) return false; // first char not found
var pos2 = parmField.indexOf(second,pos1+1);
if (pos2 == -1) return false; // second char doesn't follow first
return true; }
This function has three arguments. The first is the field we are testing, the second is the first character that needs to appear, and the third is the characters that must follow it.
The first two lines within the function test for the location of the first character. This is the equivalent of what we had in the earlier tutorial where we tested for the existence of a character within the text string. The difference here is that we are interested in where in the string that the character is found. This allows us to discard any test for at least one occurrence of the first character since this function provides that test for us. It doesn't however test that there is only one occurrence of the specified character.
The following two lines then perform exactly the same search for the second character except that only the part of the string following the first character is searched.
An example where this test would be used is when validating an email address since there should always be at least one period following the at symbol. Here is a partial validation script that checks for this as well as some of the earlier tests that we also performed on email addresses:
fld = stripBlanks(fld);
if (fld == '') return false; // test mandatory
return false; // test for only one @
if (adjacent(fld,'@.') || adjacent(fld,'.@')
return false; // test that .@ @. and .. do not occur
if (!setOrder(fld,'@','.') return false; // . must follow @
// other validations for this field to be added here