Starting Values
Join the Discussion
Often an input field is not entirely free format but has a limited range of values that must appear at either the start or end of the value that is input. Two obvious web related examples of this are links (which might have to start with http://, mailto, or ftp://) and image files (which would have to end with .gif, .jpg, .jpeg, or .png).
In this tutorial we will look at the code required to validate that the text starts with one of several specific values. Let's use the link field we mentioned above as our example:
fld = stripBlanks(fld);
if (fld == '') return false;
if (fld.indexOf('http://',0) && // no http:// at start
fld.indexOf('mailto:',0) && // no mailto: at start
fld.indexOf('ftp://',0)) // no ftp:// at start
return false;
// other validations for this field to be added here
return true;
}
This code is taking advantage of the fact that any number other than zero evaluates as true so only when the position where the first occurrence of one of the valid values is the very start of the string will one of the fld.indexOf() tests return false. If all of the tests evaluate as true (either because the value starts later in the field or is not found in the field at all) then the string does not start with any of the required values and therefore the field is invalid.

