1. Home
  2. Computing & Technology
  3. JavaScript

Only Adjacent

When you have certain characters that you only want in your input field in set combinations with certain other characters then the testing becomes slightly more complicated than just testing for the existance of adjacent characters. We need to test for the existance of the specific characters where they are not in the allowable combination. This can be done without too much difficulty as the following function shows:

function onlyAdjacent(parm,comb,chrs) {
var a = parm.split(comb);
var b = a.join('');
for (i=0; i<parm.length; i++) {
if (val.indexOf(parm.charAt(i),0) != -1) return false;
}
return true; }

This function has three arguments. The first is the field we are testing, the second is the character combination that is permitted, and the third is the characters from within that combination which are not allowed to appear outside of that combination.

The first two lines within the function remove any occurrences of the valid character combination from the field by splitting the field on those occurrences and then rejoining the pieces without that character combination. We then use a variation of the code from the isValid function that we wrote in an earlier tutorial to test what is left of the field for the characters from the third parameter not appearing in what is left of the field.

As an example of how to use this function let us consider a phone number that may have an extension indicated either by "ext" or "x". Incorporating some of the functions from our earlier tutorials we might use:

function validField(fld) {
fld = stripBlanks(fld);
if (fld == '') return false; // test mandatory
if (!oneOnly(fld,'x',false))
return false; // test for only one 'x'
if (!onlyAdjacent(fld,'ext','et'))
return false;
// test that 'e' and 't' only appear in 'ext'
// other validations for this field to be added here
return true;
}

Explore JavaScript

More from About.com

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Validating Forms
  5. Text Field Validation
  6. Only Adjacent

©2008 About.com, a part of The New York Times Company.

All rights reserved.