Basic Field Validation

Javascript, unlike many other languages, does not contain any functions to test fields for numeric or alphabetic. Instead it requires that you build these functions for yourself. Well to make it easier for you I have created a set of functions to perform some of these tests for you.

If you want to be able to test if fields contain all numbers, all lowercase letters, all uppercase letters, letters (regardless of whether they are upper or lower case) or even letters and numbers (but without special characters) then copy the following Javascript and paste it into your page (or external Javascript code).

var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyz';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
function isValid(parm,val) {
  if (parm == "") return false;
  for (i=0; i<parm.length; i++) {
    if (val.indexOf(parm.charAt(i),0) == -1) return false;
  }
  return true;
}
 
function isNum(parm) {return isValid(parm,numb);}
function isLower(parm) {return isValid(parm,lwr);}
function isUpper(parm) {return isValid(parm,upr);}
function isAlpha(parm) {return isValid(parm,lwr+upr);}
function isAlphanum(parm) {return isValid(parm,lwr+upr+numb);}

You can now test a field to see if it contains only numbers using isNum(field). To test a field for only letters use isAlpha(field), for only uppercase letters isUpper(field) or lowercase letters isLower(field). To test if it contains only letters and numbers without any other special characters use isAlphanum(field). In each case just substitute the name of the field to be tested for the word field and test the returned value - true indicates that the field contains at least one valid character and no invalid characters for the given test, false indicates that the field is either empty or contains at least one invalid character.

You can even set up your own special tests using the isValid function passing the valid values for the field in the second parameter. For example to test a field for numeric where decimals are allowed isValid(field,numb+'.'), to allow spaces as well as letters use isValid(field,lwr+upr+' '). You can even make these into standard functions by creating lines similar to the last five functions specified in the code.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate