Validating a Text Field

Just exactly what code that you need to include to valid a text field depends on what input you are asking your visitor to enter in the field. This means that the exact validation of each text field (whether an input field or textarea field) will vary. The types of validations that you might require are of various types and each of these types of validation needs to be coded separately (although sometimes you can use the result of a previous validation as input to the next).

The first thing that you need to do therefore is to work out what types of validations that you require. You can then incorporate together the appropriate code fragments that are set out below (suitably modified to meet your exact requirements) to build up the complete validation of the field. Once all of your validations are complete, you just need to add return true; to the end of the tests in order to complete the code to go into your validation function. The function will return true only when the field meets all of the validation criteria and false if it fails any test.

For the purpose of the following validations we will assume that the field you want to validate is called testField.


Mandatory Field

If it is mandatory that something be entered in the field then we need to test that the field hasn't been left blank. To do this we use the following code:

 if (testField == '') {return false;} 

If on the other hand, the field is optional but we still want to carry out further validations on the field if something has been entered then we need to return true instead.


Test for Invalid Characters

Not all characters that could be input are necessarily valid to be input into the field. Where there are characters that would invalidate the entire field if even one occurrence of any of these characters does appear then the field is invalid.

Let us assume that we want to test to ensure that there are no spaces, slashes (forward or back), semi-colons, colons, quotes (single or double), question marks, exclamation marks, parenthesis, brackets, braces, carets, or vertical bars in the field. Note that a number of these characters have special meanings to javascript so in the following code we precede them with a backslash to indicate that we want to escape their special meaning. The code to do this validation is as follows:

 var invalidChars = '\/\'\\ ";:?!()[]\{\}^|';
for (i=o; i<invalidChars.length; i++) {
if (testField.indexOf(invalidChars.charAt(i),0) > -1)
{return false;}

Just substitute the characters that you want to test as being totally invalid.


Test for at Least One Occurrence of a Character

Sometimes there is one or more characters that must be present in the field in order for it to be valid. Let's assume that we need for there to be at least one at character in the field. Here's the code to test for this and also return the position where the first occurrence is found:

 var atPos = testField.indexOf('@',0);
if (atPos == -1) {return false;}

Just substitute the character that you want to test is present.


Test for Only one Occurrence

In order to test that there is only one occurrence of a specific character, you need to first determine if the character exists at all. The code to test for at least one occurrence can be used to tell that the character exists at least once. In order to check that the occurrence that we found is the only occurrence found, we add the following code:

 if (testField.indexOf('@', atPos + 1) > - 1) {return false;} 

If the character is allowed to occur at most once but need not occur at all then instead of adding this code to the end of the previous code we substitute it in place of return false; instead.


Test that an Occurrence of One Character Follows an Occurrence of Another

Here again, we need to test for the existence of the first character before testing to see if the second character occurs later in the field. Let's assume that we expect at least one period to occur after the at sign that we've already located. The code to test for this follows:

 if (testField.indexOf('.', atPos) == -1) {return false;} 

By a simple substitution of != for the double equals in this statement we can convert the test into one that is validating that there are no periods following the at sign while periods before the at would still be allowed.


Testing Adjacent Characters

Sometimes we want to validate that two characters do not appear adjacent to one another in the field. These might be two different characters or two occurrences of the same character. Let's assume we want to test that an at sign is not adjacent to a period and that two periods are not adjacent to one another. In the case where two different characters are to be tested, we need to test both combinations as illustrated in the following code:

 if (testField.indexOf('@.',0) != -1) {return false;}
if (testField.indexOf('.@',0) != -1){return false;}
if (testField.indexOf('..',0) != -1) {return false;}


Test for a Minimum Number of Characters Following a Given Character

Sometimes a particular character is valid almost anywhere in the field except at the end of the field. For the purpose of illustration let's assume that the last period in the field must be followed by at least two other characters. The following code assumes that you have already tested that the character in question (in this case a period) exists:

 if (testField.lastIndexOf('.',0) + 2 >= testField.length) {return false;} 

Substitute the character that you want to test for as well as the number of characters that must follow.


Test that a Given Character is One of a Selected Few

This test is particularly useful for testing if a given character is alphabetic or numeric but works equally effectively with whatever set of characters are valid in the given position. For the purpose of this example we will assume that we are testing that the first character entered is alphabetic. The code to do this is as follows:

 var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (alpha.indexOf(testField.charAt(0),0) == -1) {return false;}

Just substitute your own string of valid characters and the position to test against in the charAt statement. Remember that Javascript counts the positions in a string from zero so the second position in the string is position one. Remember if using characters that have a special meaning to Javascript to place a backslash in front of them to escape that special meaning.


The above validation tests modified to test for the characters, positions, and combinations that you want to test for should allow you to build even the most complex of field validations. All you need to remember is to break the validation required up into these individual tests. If you need to repeat the same test for different character values then by all means do so, the above code is merely an illustration of how to perform each of the different types of validation (although if you put all of the above code together in order, it would make for a reasonably thorough email field validation routine).

Just one final note. These validations test that what has been entered into a field matches a given format. The code does not verify that the value entered in, for example, an email field corresponds to a valid email account, the code merely verifies that what is entered is in the correct format for that type of field and therefore might exist. In many cases this is about as far as we can reasonably go with out field validation.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow