1. Home
  2. Computing & Technology
  3. JavaScript

Ending Values

Continuing on from the previous tutorial on testing that the text starts with one of a limited range of values, let's now look at how we test that the text ends with one of a limited range of values.

This is somewhat more involved than testing at the start of the string so let's create a function that we can call to test an option for us:

function endOption(fld,val) {
return fld.substring(fld.lastIndexOf(val)) == val;
}

This function has two arguements. The first is the field we are testing and the second is a value that is valid at the end of the field. The function will return true if the field ends with the value and false if it does not.

Let's use web image files which would have to end with .gif, .jpg, .jpeg, or .png as our example and see how we would use this function to validate the end of the field:

function validField(fld) {
fld = stripBlanks(fld);
if (fld == '') return false;
if (!endOption(fld,'.gif') && !endOption(fld,'.jpg') &&
!endOption(fld,'.jpeg') && !endOption(fld,'.png'))
return false;

// other validations for this field to be added here
return true;
}
Explore JavaScript
About.com Special Features

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

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

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

All rights reserved.