You are on page 1of 4

ITEC244 - Internet Technology

Client-Side Validation using JavaScript


All about Validation

Data Validation is a very important component of designing any application. Validation involves
checking the data received by the application to make sure that it meets the specific needs of the app.
Invalid data is often submitted via forms, and this can be as the result of a simple human error or may
sometimes be part of an intentional, malicious attack on the business/website/application. Regardless
of the reason behind the invalid data, it is important that our application be able to detect and recover
from such a submission.

For this course we will implement two sets of data validation, namely:

1. Client-Side Data Validation – This is data validation that runs on the client machine and allows
us to verify that all the data is correct/valid before sending it on to the server. This is important
for several reasons:
a. it saves us time – By validating on the client’s machine rather than on the server we
remove the latency time between the two devices so processing time is optimized.
b. It saves us bandwidth – each request we send to the server uses up bandwidth.
Remember that human errors are common, and each form submission(request) has a
relatively high probability of having erroneous data. Any detected error would require a
message be sent back to the user to have the mistake(s) corrected and the form
resubmitted. If repeated errors were made, then this cycle of submitting to the server
and the server returning error messages to the client would continue... If we imagine an
app that is in use by hundreds, thousands or even millions of users at a time, and we
make it necessary for all those users to connect to the server for all our data validation
the combined utilization of bandwidth is exorbitant.
c. It saves us CPU cycles – because the task of validating is off-loaded to individual client
machines, the demand on the server processors are optimized, thereby allowing the
server to focus on work that cannot be delegated.
d. It saves us money – simply put bandwidth, and CPU time are not free.

In essence, many advantages are to be had by having the client machine take on a task which
requires only minimal effort, since each machine is responsible for validating only one user’s
data.

Lecturer: Alicia Dennis-Nagee (Last edited 202310)


1
ITEC244 - Internet Technology
Client-Side Validation using JavaScript
2. Server-Side Validation – this is a second line of defense. And it is important because:
a. Scripts may be turned off - Since client side validation tools and code runs on the client
machine, it is possible for users (or their employers) to turn scripts off in the browser. In
that case our application will function as though no validation existed, and we know that
this is not acceptable.
b. Malicious intention – It is possible for persons with malicious intentions to attack a
website by typing data directly into the URL and so completely by-pass the client form
and its validation code. We will look more at this problem in the next class.

Client Side Validation

To validate data submitted via an HTML form we will follow 3 basic steps:

1. Retrieve the form data


2. Build a regular expression to represent the pattern of allowed data
3. Test if the user data is valid
a. If data was invalid, then provide the user with feedback and prevent the form from
submitting

The following is the form we will be using for this lesson:

<form id="reg_form" name="reg_form" method="post" action="register.php"


onsubmit="return validate();" >
<fieldset>
<legend>Registration</legend>
First Name: <input type="text" name="fname" id="fname" />
<span id="fname_err" class="error"></span>
Last Name: <input type="text" name="lname" id="lname" /><br /><br />
<span id="lname_err" class="error"></span>

Email: <input type="text" name="email" id="email" />

Birth Year:
<input type="text" name="birth_yr" id="birth_yr" /><br /><br />

Gender: <input type="radio" name="gender" id="male" value="male" />


<input type="radio" name="gender" id="female" value="female"
/><br /><br />

Lecturer: Alicia Dennis-Nagee (Last edited 202310)


2
ITEC244 - Internet Technology
Client-Side Validation using JavaScript
<input type="submit" name="submit" value="Register" />
</fieldset>
</form>

Let us now go through the steps listed above.

1. Retrieve the form data

We will use the getElementById function in JS to retrieve the element whose data we want to analyze
on our form. Since we may want to remove invalid data in the element or highlight the element so that
data can be re-entered, we will opt to keep this reference variable to the element rather than just
retrieving the data directly.

let fname_element = document.getElementById('fname');

2. Build the regular expression

A Regular expression is a pattern matching utility that we will use to specify the type pf data we expect
the user to enter into a specific field. This was discussed in a separate tutorial resource in e-classroom.
In this first instance where we want to validate a user’s first name we want to allow both uppercase and
lowercase letters as well as common special characters in names i.e. ‘ ! and -. Note: because the hyphen
is used in regular expression formation to indicate a range of characters it is important that you
remember to have it listed last in the set of allowable characters i.e. the characters in square brackets.

let fname_regex = /^[a-zA-Z'!-]{2,30}$/;//matches all letters, apostrophes,


exclamation, and hyphen characters

3. Test if the user data is valid

For this section we will first use the regular expression test() function.

if(!fname_regex.test(fname_element.value)){

}

Lecturer: Alicia Dennis-Nagee (Last edited 202310)


3
ITEC244 - Internet Technology
Client-Side Validation using JavaScript
Since this function returns true when the data matches the required pattern we will construct our code
to look for non-matching values, then provide instructions to the user on how to correct the errors. Our
user feedback typically includes three things:

a. Clearing the invalid data from the form


b. Highlighting the field that where data needs to be re-entered
c. Preventing the invalid data (all the form data really) from being sent on to the server.

Let’s see how this is accomplished in today’s code:

if (!fname_regex.test(fname_element.value)){
fname_element.value = "";
fname_element.focus();
fname_element.style.backgroundColor = "#ff5555";
valid = false;
}

Note on the last line we have a flag called valid being set to false. The flag is declared globally in
this particular solution and used when we assess each of the form elements. What this does os allow us
after processing the form to determine if any of the elements contained invalid data. As long as the flag
is false at the end, we will NOT submit the form data to the server.

And that is a simple example of validating data on the client-side! This solution can be improved upon
of course, and in your sample code base you will find code to embed customized error messages for
each form field. Try to reverse engineer this code and we will discuss further in class.

Lecturer: Alicia Dennis-Nagee (Last edited 202310)


4

You might also like