Home » Web Development » 05 - Client Side Scripting Concepts
5

Javascript by Example

Learning javascript through a simple example

Now that we have taken a look at the basics, let us begin to learn Javascript through example. In this chapter, we will learn to write a function that validates the registration form in the florist web site. Validation scripts check the information the user has entered into a form against a set of valid formats and values. The form is submitted only when the user enters valid values in all fields. Let us first recap the registration form

Screenshot 5a: Florist Web Site Registration Form

Screenshot 5a: Florist Web Site Registration Form

Following are the rules pertaining to each form field:

Login: Compulsory - Should start with a letter, contain only alphabets, numbers, underscore, or hyphen and be between six and ten characters in length.

Password: Compulsory - May contain only alphabets, numbers, underscore, or hyphen and be between six and nine characters in length. The values entered in the two password fields should match

lname, fname: Compulsory - Should contain only upper and lower case letters, spaces, hyphens, single quotes, or underscores. Must start with a letter and be between 1 and 20 characters in length.

Phone Number: Compulsory - May start with a plus sign or a digit and contain 5 to 21 digits.

Gender: Compulsory - Must be selected

Favorite Flowers: Compulsory - At least one must be selected.

Birthmonth, day: Compulsory

Message: Optional. May contain anything but will be truncated to 200 characters.

First, we should make some changes in the html that will allow us to perform the validation. A 'onSubmit="return validate"' clause should be added to the form start tag. Also, dummy options containing 'select' should be added at the top of both the birth month and day lists so that we know if the user has forgotten to select the birth month and day; otherwise, the user may simply leave January 1 selected and we will never know if he or she actually has this birthday or just left the field as it was when the page loaded onto the browser.

We will use the Javascript inbuilt regular expressions facility to check if the information entered by users contains invalid characters or formats. Although other validation methods may be used, using regular expressions is best simply because seaching long strings and matching patters is what regular expressions are meant for. Regular expressions are patterns that may be searched for within strings of characters. Mastering regular expressions involves a lot of practice. A trial and error approach is the only one that works when it comes to specifying the right pattern. There are several standard shorthand codes that may be used while specifying patterns. Let us look at some of these: