Tutorial Index
















Need Help?

WA's Ultimate JavaScript Tutorial

Lesson 6-Validating forms

One of the most practical uses of JavaScript is validating forms. Since we've just learned how to access forms, in this section, we will talk about:

Introduction to validating forms

Lets first define what is meant by validating forms. Well, using JavaScript, you can check what a user enters into a form, intercept a form from being submitted and ask the user to retype or fill in the unfilled entries of a form before re-submission. Before, you would have to do this using CGI, which is both something I don't want to touch, and something you don't want to either...you with me? Anyone?

Using the onBlur event handler

We will now introduce two more event handlers, ones especially for forms, that are used commonly when doing form validations.

Additional Event handlers for forms
onblur:   Executes JavaScript whenever a user moves, with the mouse the focus away from an element within a form. In other words, whenever a person first clicks an element, and then clicks anywhere outside of it.
onsubmit:   Executes JavaScript whenever someone clicks the "submit" button.

Ok, you need clarification. Onblur is used when you want to check each element (ie: text, textarea boxes ) individually, and ask the user to correct the input before moving on to the next box. The other event, onsubmit, validates the form at the end, as the user presses the submit button. I prefer the later, but its up to you.

Ok, lets see exactly how onblur works. Ok, we're going to write a script that checks the first text box , and asks for correction as soon as text has been entered and the user moves the focus into another box (assuming the person has entered "wrong" data.) Here we go:

Enter your email address: (Try entering something without the "@", and you'll get a alert telling you to re-enter the data as you proceed to the Feedback box.)

Feedback please:

  <script>
function emailcheck()
{
var string1=document.example.email.value
if (string1.indexOf("@")==-1)
.{
.alert("Please input a valid email address!")
.document.example.email.focus()
.}
}
</script>

<form name="example"><input type="text" size="20" name="email" onblur="emailcheck()">
<strong>Feedback please:</strong>
<textarea name="S1" rows="2" cols="20"></textarea>
<input type="submit" name="B1" value="Submit">
</form>

Ok, lets have a look at what's inside the <script> tags.

  • We defined a function called emailcheck() that'll be called by the onblur event hander when the user clicks elsewhere away from that element.
  • We copied the value of the box into "string1". Why? Simply for easier reference, you don't have to do this.
  • Here comes the part that requires explaining. What is:
    "string1.indexOf("@")==-1" in the code? Well, first of all, you need to understand that all data entered into a text, text area box are string variables-variables that are treated as characters, instead of numbers. For ex, "Hello there" or "12343" are strings, 12343 is a number. Now, here is the surprise: string itself is also an object. If that's the case, that means it has methods/properties. One of the methods, you might have guessed it, is indexOf("the char you are looking for"). Using this method, we can search every char within a string and look for what we want. If it finds it will return the position of the char within the string. If it doesn't, it will return -1. Therefore, "string1.indexOf("@")==-1" basically means: "if @ is not in the string, do this:
    alert("Please input a valid email address!")
    document.example.email.focus()
    What's the thing in red? Well, focus() is a method of the text box, which basically forces the cursor to be at the specified text box, which is like the user clicking inside the text box with the mouse.Why do we need this? If we didn't, the only thing the users that entered bad data will see is the message "Please input a valid email address!" but THAN still allowed to move on onto the second box, and submitting the form. That's merely a slap on the face, and will not truly screen out those that are determined to not follow the rules. However, if we use the focus() method, the focus will be set back to the box containing errors, and will only allow users to proceed after it has been corrected.
  • This is not a fool proof validation...in fact, you could enter "@sprynet" and get away with it. Ok, that can always be corrected!

If you've been playing around with the onblur event handler, even with simply the above example, it can be very annoying at times; the better way is to simply defer the checking until a user presses the submit button, and check for errors all at once in one scoop. That's how the onsubmit handler comes in.

onsubmit

The "onsubmit" handler is inserted inside the <form> tag, and not inside any one element, unlike "onblur." For example: <form name="george" onsubmit="what_ever"> Lets do an example:

Enter Your name (*required) If you leave the required sections blank, as you click submit, you will be forced to come back and fill this box in.

Feedback please: (*required)

Your home address (*NOT required)

  <script>
<!--
function validate()
{
if ((document.example2.naming.value=="")||
(document.example2.feed.value==""))
.{
.alert ("You must fill in all of the required .fields!")
.return false
.}
}
//-->
</script>

<form name="example2" onsubmit="return validate()">

<input type="text" size="20" name="naming">

<strong>Feedback please: (*required)</strong>

<textarea name="feed" rows="3" cols="25"></textarea>

<strong>Your home address (*NOT required)</strong>

<input type="text" size="35" name="address">

<input type="submit" name="B1" value="Submit">

</form>

Some every important things here:

  • document.example2.naming.value=="".What is the quotation in orange? That is used to indicate an empty value-something that contains nothing. It is important that you distinguish between "" and " " The later means "1 empty space", as opposed to "empty value". The later is a char-namely, a space.
  • What is "return true", "return false"? This is what's used to actually allow, or stop the form from submitting, respectively. This is how javascript controls the submitting of a form. By default, a form will return true. (Submit the form). This is a important point-for example, by using the above knowledge, you can apply it to also stop a link from completing upon clicking. Ok, I'll show you an example:
    <a href="normal.htm" onclick=
    "return false">Click here, it won't work!</a>
    Click here, it won't work!
    By returning false, we prohibit the action from completing!
  • Now, a confusing point may be-onsubmit="return validate()" why return validate()? Wouldn't that be like a double return? No. Function validate only returns "true/false". You need "return true/fast" to actually manipulate whether a form submits or not. That's why we have to return validate(), as opposed to just validate().

Ok, in this section, we ran into the string object, so lets list all its properties and methods for quick glance:

properties Methods
length
anchor
big
blink
bold
fixed
fontcolor
italics
small
strike
sub
sup
charAt
indexOf, lastIndexOf
link
split
substring
toLowerCase
toUpperCase

What's next? Time is precious, so lets look at that...

Lesson 7