1. Home
  2. Computing & Technology
  3. JavaScript

One and Only One

Join the Discussion

Questions? Comments?

It is all very well validating that a field only contains certain characters but there will be times when you need to test that a specific character appears a set number of times as well. Examples of this include numbers containing decimals which can only have one decimal point and email addresses that must have one and only one @ symbol within the entered string.

If we consider the first example then the first thing we need to do is to add the decimal point to the set of characters that we consider to be valid. We can do this by adding the following function to those we already have:

function isDecimal(parm) {return isValid(parm,numb+'.');}

That allows us to validate for numbers as well as the decimal point but a number with no decimal points or ten would still be accepted as valid. We need to add another function to test whether a particular character appears in the field at all and whether it appears multiple times. Here's our new function:

function oneOnly(parm,chr,must) {
var atPos = parm.indexOf(chr,0);
if (atPos == -1) {return !must;}
if (parm.indexOf(chr, atPos + 1) > - 1) {return false;}
return true; }

This function has three arguments. The first is the field we are testing, the second is the character we are testing for, and the third is true if the character must exist in the field and false if it is optional. The first line in the function finds the position of the first occurrence of of the character within the field or -1 if the field doesn't contain the character. The second line will return true if the character doesn't exist but is optional or false if the character must exist and is not found. The third line tests for a second occurrence of the character within the field.

A decimal point is optional so the code we add to test for only one occurrence does not have to confirm that a decimal point actually exists. If we add these tests to the code from he previous tutorials we get the following:

function validField(fld) {
fld = stripBlanks(fld);
if (fld == '') return false; // test mandatory
if (!isDecimal(fld)) return false; // test decimal numeric
if (!oneOnly(fld,'.',false))
return false;
// test for only one decimal point
// other validations for this field to be added here
return true;
}

A call to this same routine would validate that an email address contains the required @ symbol using the following call:

if (!oneOnly(fld,'@',true) return false;
Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

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

All rights reserved.