Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat.

free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class">

Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat. free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class

<Code_Punk>'s

Advanced JavaScript Lesson 17:
Parsing Text

Code Tutorials



Site Development



Downloads



Help!!



Home


Finding & Handling Errors

At the heart of all form validation is the detection and handling of errors. Error detection centers around parsing, or analyzing, the text strings passed from a form. The best overall approach in most cases is to use IF statements to check for errors. If errors are found, an error routine is run. If one test is passed, another IF is run, and so forth until all possible errors are tested.

Below is a step-by-step overview of the form validation process:

1) Assign form data to JavaScript variables for use in validation statements.

2) Determine what qualifies as an error for all of the fields on a form.

3) Determine how to detect this error in an IF statement's conditions (in the parentheses).

4) Determine how you want to handle errors. Make a separate function for this error control. That way each IF can call on this function without you having to type the error control routine in each IF. More on this in this tutorial.

5) Determine what you want to happen when all IF tests are passed and the data is good.

6) Code your validation with the rough outline below:

// var assignment

var name = document.form1.box1.value;
var another_variable = document.form1.box2.value;
...

// if section

function test_for_errors(){
if (error condition 1){error_routine();return}
if (error condition 2){error_routine();return}
if (error condition 3){error_routine();return}
...

//data is good

Use data or send it to further processing
}//ends testing function

//error control

function error_control(){
Whatever alert() boxes or such you'll use to point out the error and reset the form
}//ends error_control function

Note that there are three main sections of code: assigning form data to variables, testing for errors and processing good data, error control in a separate function.

Some of the above, like calling on a function from another function, might look strange right now. Don't worry. That's all covered in this tutorial. Lets start making this example that tests for a valid email address by analyzing the entered text's format.

indexOf()

"Parsing text" means breaking down a string into its component characters and substrings and analyzing them. JavaScript has many methods to help us do this. We can see if a particular character or substring is present and where it's located in a string.

We'll begin by making this simple Email Validator. This program asks for an email address. When entered, the string holding the email address is checked for the "@" symbol and "." (dot) that are unique to email addresses.

Then we'll test to make sure there is text before and after the "@".

This program is centered around JavaScript's "indexOf()" and "split()" methods. To understand text parsing, it is important to realize that JavaScript views strings as an array of characters. This is like the arrays we've previously worked with. The first character is at the "0" (zero) position. The second character is at the "1" position, etc.

When we use the "indexOf()" method, we put a character in the parentheses like this:

string_name.indexOf("@")

The above would look for the "@" character in a string assigned to the variable "string_name". It returns the position of the character. Say "string_name" was my email address -- code_punk@hotmail.com. Using "indexOf("@")" would return a 9. The "@" character is in the ninth position in my email address. Remember that the counting starts at zero. The "indexOf(".")" would show that the dot in my email address is at position 17.

If you look for a character and it's not in the string, a "-1" is returned. That's neat because an "indexOf()" returning -1 means that the character is not present in the string. This is how our simple email address validation is set up.

Start making the example by coding the form to accept the email address. Make the submit button and add an ACTION to your <form> tag that leads to a checking function. I called my function "check()".

Below is the code that checks to see if an "@" and "." are present.

if (the_string.indexOf("@") > -1 && the_string.indexOf(".") > -1){

code to run if "@" AND "." are present
}

else{
code to run if either "@" and "." are missing or both are missing.
}

The IF statement above first checks to see if the "@" character is in "the_string". If it is, the "indexOf()" value will be zero or more. A "-1" would indicate that the "@" is missing. That's what we're testing for first.Then we use the logical AND (&&) to test for the presence of the dot, too. Both conditions must exist before the IF code will run.

The above checks for correct data. Form validation, however, is mostly centered around checking for incorrect data, or errors.

An Alternative

Most of the time when we're checking for errors in a text string, we want to use the IF to check for errors instead of checking for proper entries. In the previous section, we checked for the presense of "@" and ".". In this section, and in our example we'll be checking for the absence of "@" or ".".

To check for absence, we check to see if the "indexOf()" is less than 0 (<0). We also use the logical OR (||) between the conditions. We use logical OR because an error has occurred if either character is absent:

if (address.indexOf("@") < 0 || address.indexOf(".") < 0)

The above checks to see if either the "@" or "." are missing. If either are missing, it is an invalid email address and an error.

Using a Sub-Routine

Before moving on in our email address validation, lets learn one of the most convenient features of JavaScript -- the Sub-Routine. A sub-routine is just a function that is referred to by another function (parent function). In our case, we'll be using the same error alert() box and routine for any error. We'll be running a couple of tests, but there is no reason we have to code the error control statements twice. Imagine if you had a dozen or more IFs!?

We can code the error control only once and put it in its own function. Then just refer to the function when an error is detected. First, lets code our error function:

function error_report(){

alert ("Invalid email address. Please try again.");
document.form1.addy.value = "";
document.form1.addy.focus();
}

The above is a pretty simple error function. It pops up an alert() box explaining an error has occurred. Next, it clears the box of text. Finally, it focuses (focus()) the box for another try.

To send an error our "error_report()" function (sub-routine), we just use the function name in the IF statement:

function check(){

var address = document.form1.addy.value;

if (address.indexOf("@") < 0 || address.indexOf(".") < 0){
error_report()
}
}//ends check() function

function error_report(){

alert ("Invalid email address. Please try again.");
document.form1.addy.value = "";
document.form1.addy.focus();
}

The above "check()" function will call and run the "error_report()" function when the IF condition(s) exist. All we had to do was to type in the error function's name and parentheses. You can even pass parameters between functions by adding parameters inside the function's parentheses as we've done in the past.

Here's a breakdown for an email address missing a "@". First the error is detected in the IF's conditions to test. The IF statement is run which is "error_report()'s" function call. Now "error_report()" is run all the way through.

After the "error_report()" function has run, the script goes back to the point right after the function call. If we had more statements in the IF brackets after "error_report()", they would then be run. The important thing to remember is that things won't necessarily stop after "error_report()" is run.

Genrally speaking, once an error is detected and an error sub-routine is run, we want the script to stop. There is no need for further analysis once an error is detected. In fact, if the script keeps running, it might lead to errors. Next, we'll see how to stop a script while it is running.

Using Return

To stop a JavaScript from continuing and return to the page, we use the "return" statement. This "returns" the viewer back to the page and stops the JavaScript from running. It does a lot more, too, like passing values between different functions. For now, though, we'll be using "return" just to stop the script.

We'll stop our script after an error has been detected and the "error_report()" function has run. Remember that after the "error_report()" function has run, the script goes back to the next line of the parent function (the "check()" function that called "error_report()".

function check(){

var address = document.form1.addy.value;

if (address.indexOf("@") < 0 || address.indexOf(".") < 0){
function error_report();
return; }
}//ends check() function

function error_report(){

alert ("Invalid email address. Please try again.");
document.form1.addy.value = "";
document.form1.addy.focus();
}

When the above script runs and an error is detected, the "error_report()" function will be called, run, and return to the parent function. It will start to run the next line below the line that called the sub-routine ("error_report()"). In this case, that line is "return", which ends the JavaScript and returns the viewer to the regular page.

Using a sub-routine and "return" will become more important as we add further tests (IFs) to our "check()" function.

split()

In addition to checking for the presense of "@" and ".", we'll have our script check to make sure there's some text included as well. We'll make a simple check to make sure that there are text strings on both sides of the "@" using "split()".

The "split()" method breaks up a string into substrings based on a character in the string. Each substring can be accessed as an array of the overall string. Lets look at an example.

var the_string = "Code Punk";

Now lets split the string at the space (" ") to make "Code" and "Punk" substrings:

var the_string = "Code Punk";

var broken_up_string = the_string.split(" ");

Note the second line. We've applied the "split()" method to "the_string". It will be split at each space. The space is between the quotes in the parentheses. This splits our string into two parts along the space.

One string holds "Code" and the other "Punk". The space is not included in either string. Both of these strings are held in an array assigned to the variable "broken_up_string". We'd access these values like this:

var the_string = "Code Punk";

var broken_up_string = the_string.split(" ");

var part_one = broken_up_string[0];
var part_two = broken_up_string[1];

Notice that accessing the substrings caused by the "split()" method is just like accessing any array object. We just type in the array name and then add [number]. The counting begins at 0.

The variable "part_one" now holds the string "Code". The "part_two" variable is assigned "Punk".

You can have any number of substrings based on what character you choose as the index of the "split()" method. Using "split("a")" on "Great Expectations" would make three substrings numbered 0-2. These strings would be "Gre", "t Expect", and "tions". The character used as "split()'s" index is not included in the substrings.

Once the different substrings are assigned to variables, you can use these variables to manipulate the substrings any way you want. Try making this example which takes a name and then displays it backwards.

Using split()

Now lets apply the "split()" method to our example. We'll use it to check for text on both sides of the "@" character.

First lets "split()" the address around the "@" character:

function check(){

var address = document.form1.addy.value;

if (address.indexOf("@") < 0 || address.indexOf(".") < 0){
function error_report();
return; }

var addy_parts = address.split("@");

}//ends check() function

function error_report(){

alert ("Invalid email address. Please try again.");
document.form1.addy.value = "";
document.form1.addy.focus();
}

The above will split "address" into substrings on each side of the "@" character. This will leave us two substrings in a valid email address. The text before the "@" will be "addy_parts[0]" and the text after the "@" will be "addy_parts[1].

Now we'll use the "length" property of text strings to make sure that some text exists in both strings. More accurately, we're testing to see if there is no text in either string (an error):

function check(){

var address = document.form1.addy.value;

if (address.indexOf("@") < 0 || address.indexOf(".") < 0){
function error_report();
return; }

var addy_parts = address.split("@");
if (addy_parts[0].length < 1 && addy_parts[1].length < 1){

error_report();
return;
}
}//ends check() function

function error_report(){

alert ("Invalid email address. Please try again.");
document.form1.addy.value = "";
document.form1.addy.focus();
}

The above brings up many important points. First, note that we checked for the error in an IF statment. We did not check for the "good" or non-error condition. We also used the error_report() sub-routine just like in the previous IF test.

Also notice the placement of the second IF test. It's right below the first one. The first IF will make sure that there's an "@" to split around. This prevents a possible error if no "@" was present.

This also makes clear why we need to use a "return". Had we not used a "return" in the first IF, the script would continue running the second IF. There would be no "@" (or anything else due to "error_report()") and an error would occur in the script.

Using "return" in the first IF prevents the second IF from running if the first IF detects an error. (That sounded "iffy".) This is the critical point in using an error control sub-routine. The IFs must be properly ordered and a "return" used to stop analysis after an error is found.

The "Good" Display

The final part coded is the alert() box that states you've entered a valid email address. This is at the bottom of the IFs, and still in the "check()" function. It's at the bottom because you want all of the possible errors detected before the input is accepted as good.

function check(){

var address = document.form1.addy.value;

if (address.indexOf("@") < 0 || address.indexOf(".") < 0){
function error_report();
return; }

var addy_parts = address.split("@");
if (addy_parts[0].length < 1 && addy_parts[1].length < 1){

error_report();
return;
}

alert("Thank you for entering a valid email address.");
}//ends check() function

function error_report(){

alert ("Invalid email address. Please try again.");
document.form1.addy.value = "";
document.form1.addy.focus();
}

Summary & Exercises

When validating strings from a form, use a main function of IFs to test for all possible errors, not conditions which are correct. At the end of the IFs, code whatever you want to happen when the data is correct.

Make and use error routines in a separate function(s) that can be used repeatedly when an error is detected by an IF. This saves you having to code the same or similiar routine in each IF statement. Remember that you can pass parameters to in the sub-routine's function call to bring up a specific message for each error.

There are all sorts of JavaScript methods to help you analyze text from input. The most important of these are the ones that can search the string and break a string up into substrings.

Like other arrays, strings have a "length" property with a value of the number of characters in the string. This includes spaces. Empty, or null, strings have a length of 0.

The "indexOf()" method will find the position of a character or substring in a string. If the character or substring is not present, it will return a -1.

The "split()" method breaks a string into substrings based on the character(s) put in the parentheses (and in quotes). This character(s) is called the "index" and is not included in the substrings. The substrings are accessed just like any array elements.

Try making this email validator. It checks for the presence of "@" and ".". It also checks to make sure there's some text before and after the "@".

Once you get that working, add some more tests of your own. Make the script reject any email address with the letter "a" or "z" in it. (Just add an IF and send it to "error_report()".)



To Next Advanced JavaScript Lesson

Back To Advanced JavaScript Index