Broad Network


Introduction to Form Field Validation with ECMAScript

ECMAScript Basics - Part 13

Forward: In this part of the series, I introduce you to HTML Form Field Validation with ECMAScript.

By: Chrysanthus Date Published: 25 Jul 2012

Introduction

This is part 13 of my series, ECMAScript Basics. In this part of the series, I introduce you to HTML Form Field Validation with ECMAScript.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Validation
When a user puts in data into a form field, it is possible for him to make a mistake or even try to put in wrong data. Some of these mistakes or deliberate wrong data input can be detected by code. For example, if datum is supposed to start with a letter, and he starts it with a number, you can write code to detect that. If a password is supposed to be a minimum of 6 characters and a maximum of 20 characters, you can write code to detect that. Each datum would have its own set of rules that determine whether it is valid or not. Based on such rules you can write code that will determine whether the datum is valid or not. I will not go into the details in this article. I only introduce to you, how ECMAScript handles validation.

The HTML onsubmit Attribute
The HTML form has an attribute called the onsubmit attribute. This is an event attribute. The event is triggered when the Form Submit button is clicked. The value of this attribute is a call to an ECMAScript function. This attribute (and its value) is optional. When the attribute is omitted, and you click the form submit button, the form is submitted (sent to the server).

If the attribute is present (that is, call to an ECMAScript function is present), the function can check if the form fields are valid or not. If the fields are valid, then the form is submitted. If any of the fields is not valid, then the form is not submitted, and the required error message is displayed in an alert box. The main feature to achieve this is the ECMAScript return statement.

The return Statement
The return statement without value is:

    return;

The return statement with value is:

    return value;

The value can be a literal, e.g. true or false. When true or false is used as value, it does not need quotes.

Whether or not the return statement returns a value, when a function is executing and it meets the return statement, the function stops at the return statement. This is not a fault; it is the work of the return statement. At that point, if the return statement has a value, the value is returned. If the value is true, it means everything went well, and the browser can continue as expected. If the return value is false, it means the browser should stop until there is some action from the user. In the case of Form submission, if any field is not valid, false should be returned. If all fields are valid, true is returned.

The story does not end there: the value of the onsubmit attribute is not an ordinary call; it is,

    "return functioName([params])"

You begin the value with “return” and then space.

Syntax for reading Form Control Values
Some Form controls (fields) have the value attribute; others do not. For those that have the value attribute, you read the value with the following syntax:

    var valueRead = document.getElementById(ID).value;

You write the value with the following syntax:

document.getElementById(ID).value = valueWritten;

where ID is the ID of the control in quotes.

Example
Let us look at a simple example. In this example there is a form with four fields: First Name field, Last Name field, Email field and Message field. You are the one who is supposed to decide on the rules for validation (there are some classical rules though). To make things simple, let us have just one and the same rule for three of the fields. The rule is that the First Name field, Email field and Message field cannot be empty. So, we shall write code to check if each of these three fields is empty. The Last Name field can be empty, so it does not need any code.

Here is the complete code for the simple example:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<form method = "post" action = "http://www.somewebsite.com/cgi-bin/file.exe" onsubmit = "return validate()">
    <table>
        <tbody>
            <tr>
                <td>First Name:</td><td><input type="text" name="firstName" id="fn"></td>
            </tr>
            <tr>
                <td>Last Name:</td><td><input type="text" name="lastName" id="ln"></td>
            </tr>
            <tr>
                <td>Email:</td><td><input type="text" name="email" id="em"></td>
            </tr>
            <tr>
                <td>Message:</td><td><textarea name="msg" cols="30" rows="3"

id="msg"></textarea></td>
            </tr>
        </tbody>
    </table>
    <button type="submit">Send</button>
</form>

<script type="text/ECMAScript">

    function validate()
        {
            if (document.getElementById('fn').value == "")
                {
                    alert('The First Name field cannot be empty.');
                    return false;
                }
            else if (document.getElementById('em').value == "")
                {
                    alert('The Email field cannot be empty.');
                    return false;
                }
            else if (document.getElementById('msg').value == "")
                {
                    alert('The Message field cannot be empty.');
                    return false;
                }
            else
                return true;
        }

</script>

</body>
</html>

From what I have said above, the code should be self-explanatory. We have validated the first name and not the last name. This suggests that the first name is more important than the last name. In some countries, the last name is actually more important than the first name.

To fully understand validation coding, you need to learn what is called the HTML DOM and ECMAScript Regular Expressions. I will comment on these later.

Let us stop here and continue in the next part of the series.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message