1. Home
  2. Computing & Technology
  3. JavaScript

Alphabetic and Numeric

Join the Discussion

Questions? Comments?

Related Resources

Mandatory Fields

Javascript does not contain functions that test specifically for alphabetic or numeric content but we can easily provide these functions for ourselves. Just add the following code into the head section of your page:

var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyz';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function isValid(parm,val) {
if (parm == "") return true;
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
continued from previous line isValid(parm,lwr+upr+numb);}

This gives us a set of functions that can be used to validate that fields contain only numbers, only lowercase alphabetics, only uppercase alphabetics, only alphabetics (irrespective of upper or lower case), and any alphabetic or numeric characters (but not punctuation or special characters).

We can easily add any further specific character tests to this by specifying the valid characters in the second parameter of an additional isValid function call.

The other thing that we need to do is to actually add the appropriate call to the function that we created in the Mandatory Field tutorial to perform our field validation. If we are testing for a mandatory and numeric field the code will be as follows:

function validField(fld) {
fld = stripBlanks(fld);
if (fld == '') return false; // test mandatory
if (!isNum(fld)) return false; // test numeric
// other validations for this field to be added here
return true;
}

If the field is required to be numeric but is not mandatory then you would use the same code except that the "test mandatory" line would be left out.

You can easily change this to test the field for lowecase, alphanumeric or whatever you require by substituting the appropriate function call.

Explore JavaScript

More from About.com

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Validating Forms
  5. Text Field Validation
  6. Alphabetic and Numeric Validations

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

All rights reserved.