1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Adjacent Characters

Some times certain characters are only valid when they appear next to certain other characters. Other times certain characters are valid only when they don't appear next to certain other characters. We can test for these using the following function:

function adjacent(parm,chrs) {
return(parm.indexOf(chrs,0) != -1);

This function has two arguments. The first is the field we are testing and the second is the character combination we are testing for. The function finds the position of the first occurrence of of the character string within the field or -1 if the field doesn't contain the string and then returns true if the the characters are found adjacent to one another in the field and false if they are not.

As an example of how to use this function let us consider an email address which may contain both an at (@) symbol and periods (.) but not adjacent to one another. 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,'@',true))
return false; // test for only one @
if (adjacent(fld,'@.') || adjacent(fld,'.@')
|| adjacent(fld,'..'))
return false;
// test that .@ @. and .. do not occur
// other validations for this field to be added here
return true;

As you can see from this example we need to call the function once for each combination of adjacent characters that we want to disallow and so to check that we don't have a period adjacent to either side of the at symbol or adjacent to another period we need three separate tests.

See More About

©2016 About.com. All rights reserved.