0% found this document useful (0 votes)
32 views27 pages

Session Eleven - Javascript Control Structures and Form Validation

This document discusses control structures and form validation in JavaScript. It begins by outlining the objectives of understanding JavaScript control structures and operators, and learning how to validate user input on HTML forms. It then provides an introduction to conditional and iterative statements in JavaScript. The bulk of the document explains different JavaScript control structures like if/else statements, switch statements, for, while, and do-while loops. It also covers DOM selectors like getElementsByTagName(), getElementsByClassName(), getElementById(), querySelector(), and querySelectorAll() that can be used to select HTML elements. Examples are provided for each control structure and selector.

Uploaded by

brian vaner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views27 pages

Session Eleven - Javascript Control Structures and Form Validation

This document discusses control structures and form validation in JavaScript. It begins by outlining the objectives of understanding JavaScript control structures and operators, and learning how to validate user input on HTML forms. It then provides an introduction to conditional and iterative statements in JavaScript. The bulk of the document explains different JavaScript control structures like if/else statements, switch statements, for, while, and do-while loops. It also covers DOM selectors like getElementsByTagName(), getElementsByClassName(), getElementById(), querySelector(), and querySelectorAll() that can be used to select HTML elements. Examples are provided for each control structure and selector.

Uploaded by

brian vaner
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Technical University of Mombasa

CIT 2201: WEB DEVELOPMENT II

SESSION ELEVEN: CONTROL STRUCTURES AND FORM


VALIDATION
11.0 Objectives

1. To understand how the various control structures work in JavaScript.


2. To identify how the various operators can be used in JavaScript.
3. To learn how to validate user inputs when handling HTML forms using
JavaScript.

11.1 Introduction

Control structure actually controls the flow of execution of a program. JavaScript


basically, has two types of control statements as follows:

 Conditional Statements: based on an expression passed, a conditional


statement makes a decision, which results in either YES or NO.
 Iterative Statements (Loop): Until and unless the expression or the condition
given is satisfied, these statements repeat themselves.

We ca also use JavaScript to validate user input on a form such as looking for empty
fields, email validation , password validation etc.

TUM is ISO 9001:2015 Certified


11.2 JavaScript Control Structures

11.2.1 If… Statement

IF statement is a conditional branching statement. In 'IF' statement, if the condition


is true, a group of statement is executed. And if the condition is false, the following
statement is skipped.

Syntax:

if (condition)
{
//code to be executed
}

Example:

<html>
<body>
<script type="text/javascript">
var num = prompt("Enter Number");
if (num > 0)
{
alert ("Given number is Positive!!!");
}
</script>
</body>
</html>

11.2.2 If…Else Statement

If – Else is a two-way decision statement. It is used to make decisions and execute


statements conditionally.

Syntax:

if (condition)

TUM is ISO 9001:2015 Certified


{
//Statement 1;
}
else if(condition)
{
//Statement 2;
}
else
{
//Statement 3;
}

Example:

<html>
<head>
<script type="text/javascript">
var no = prompt("Enter a Number to find if Odd or Even");
no = parseInt(no);
if (isNaN(no))
{
alert("Please Enter a Number");
}
else if (no == 0)
{
alert("The Number is Zero");
}
else if (no % 2)
{
alert("The Number is Odd");
}
else
{
alert("The Number is Even");
}
</script>
</head>
</html>

TUM is ISO 9001:2015 Certified


11.2.3 Switch Statement

Switch is used to perform different actions on different conditions. It is used to


compare the same expression to several different values.

Syntax:

switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
case condition 3:
//Statements;
break;
.
.
case condition n:
//Statements;
break;
default:
//Statement;
}

Example:

<html>
<head>
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");
switch (day)
{
case (day="1"):
document.write("Sunday");
break;
case (day="2"):
document.write("Monday");
break;

TUM is ISO 9001:2015 Certified


case (day="3"):
document.write("Tuesday");
break;
case (day="4"):
document.write("Wednesday");
break;
case (day="5"):
document.write("Thursday");
break;
case (day="6"):
document.write("Friday");
break;
case (day="7"):
document.write("Saturday");
break;
default:
document.write("Invalid Weekday");
break;
}
</script>
</head>
</html>

11.2.4 For Loop

For loop is a compact form of looping.

It includes three important parts: Loop Initialization, Test Condition and Iteration

Syntax:

for (initialization; test-condition; increment/decrement)


{
//Statements;
}

Example:

<body >
<script type="text/javascript">

TUM is ISO 9001:2015 Certified


// program to display text 4 times
const n = 5;
// looping from i = 1 to 4
for (let i = 1; i < n; i++) {
document.write(`I love JavaScript.<br>`);
}
</script>
</body>

11.2.5 While Loop

While loop is an entry-controlled loop statement. It is the most basic loop in JavaScript.

It executes a statement repeatedly as long as expression is true. Once the expression becomes
false, the loop terminates.

Syntax:

while (condition)
{
//Statements;
}

Example:
<body >
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
</body>

TUM is ISO 9001:2015 Certified


11.2.6 Do-While Loop

Do-While loop is an exit-controlled loop statement. Similar to the While loop, the
only difference is condition will be checked at the end of the loop. The loop is
executed at least once, even if the condition is false.

Syntax:

do
{
//Statements;
}
while (condition);

Example:

<body >
<script type = "text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");


do {
document.write("Current Count : " + count + "<br />");
count++;
}

while (count < 5);


document.write ("Loop stopped!");
//-->
</script>
</body>

11.3 JavaScript DOM Selectors

DOM means Document Object Model. DOM Selectors, as the name suggests is used to select
HTML elements within a document using JavaScript.

TUM is ISO 9001:2015 Certified


There are 5 ways in which you can select elements in a DOM using selectors.

 getElementsByTagName()
 getElementsByClassName()
 getElementById()
 querySelector()
 querySelectorAll()

All those methods are properties of the document object. So in order to use one, we
should prefix those elements with the document object as,

document.getElementsByTagName()

document.getElementsByClassName ()

document.getElementById ()

document.querySelector ()

document.querySelectorAll ()

11.3.1 getElementsByTagName ( )

This method returns all the elements that matches the specified Tag name. The
getElementsByTagName() method accepts a tag name and returns a live
HTMLCollection of elements with the matching tag name in the order which they
appear in the document.

Syntax:

let elements = document.getElementsByTagName(tagname);

Parameters:

 elements is a collection of all the found elements in the order they appear with
the given tag name.

TUM is ISO 9001:2015 Certified


 tagname is a string representing the name of the elements. The special string
“*” represents all elements.

Example:

<body style="text-align: center">


<h2>
DOM getElementsByTagName()
</h2>

<p>This example demonstrates use of getElementsByTagName.</p>


<button onclick="tag_name()">Click to try it</button>

<script>
function tag_name() {
var doc = document.getElementsByTagName("p");
doc[0].style.background = "blue";
doc[0].style.color = "white";
}
</script>
</body>

11.3.2 getElementsByClassName ( )

This method returns all the elements that matches the specified Class name.

Syntax:

document.getElementsByClassName(classname);

Example:

<body>
<h2>DOM getElementByClassName() Method</h2>
<div>
<h4 class="example">div1</h4>
<h4 class="blueBorder example">div2</h4>
<h4 class="greenBorder example">div3</h4>
<h4 class="example">div4</h4>
</div>
<script>
document.getElementsByClassName('greenBorder example')[0].style.border =

TUM is ISO 9001:2015 Certified


"10px solid green";
document.getElementsByClassName('blueBorder example')[0].style.border =
"10px solid blue";
</script>
</body>

11.3.3 getElementsById ( )

Here, the selection is based on the Id name. And this seems to be similar to Tag name
& Class name selector but there’s a difference in how many elements this selector
selects. In all the above selectors, a list of all matching elements is returned. But this
selector returns only the first matched element while ignoring the remaining.

<body>
<p id="mark">This is a paragraph of text.</p>
<p>This is another paragraph of text.</p>
<script>
// Selecting element with id mark
var match = document.getElementById("mark");
// Highlighting element's background
match.style.background = "lightblue";
</script>
</body>

NOTE: And this is where getElementById differs from getElementsByTagName and


getElementsByClassName. getElementById returns the element as soon as it gets a
match. Also you can notice a difference in the name of the selector, the word element
is singular in getElementById while it’s plural in other selectors getElementsByTagName
& getElementsByClassName.

11.3.4 querrySelector ( )

This one returns the first element that matches the specified CSS selector in the
document. It returns only a single element that matches the specified classname. If it
does not find any matching element, it returns null.

TUM is ISO 9001:2015 Certified


Syntax:

let element = document.querySelector("CSS selector");

 CSS selector-A string containing one or more selectors to match. This string
must be a valid CSS selector string; if it isn't, a SyntaxError exception is thrown

CSS Selector Examples

 class selector: document.querySelector(".class-name");


 tag selector: document.querySelector("div");
 id selector: document.querySelector("#main");

Example:

<html>
<head>
<title>DOM Examples</title>
<style>
.main {
font-weight: bold;
}
</style>
</head>
<body>
<h1>querySelector Example</h1>
<p id="description" class="main">
querySelector's power is exceeded only by it's mystery.
</p>
<div id="response">
It's not that mysterious, querySelector selects elements
using the same rules as CSS selectors.
</div>
<script>
// selects the <p> using class selector
let main = document.querySelector(".main");
document.write(main.innerHTML.trim());
main.style.color = "blue";

// Selects the <div> using tag selector


let response = document.querySelector("div");
document.write(response.innerHTML.trim());

TUM is ISO 9001:2015 Certified


response.style.color = "red";
</script>
</body>
</html>

NOTE:

The innerHTML property sets or returns the HTML content (inner HTML) of an
element. It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.

The innerText property sets or returns the text content of an element. The innerText
property can be used to write the dynamic text on the html document. Here, text will
not be interpreted as html text but a normal text. It is used mostly in the web pages
to generate the dynamic content such as writing the validation message, password
strength etc.

<script type="text/javascript" >


function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>

The trim() method removes whitespace from both ends of a string and returns a new
string, without modifying the original string.

TUM is ISO 9001:2015 Certified


11.3.5 querrySelectorAll ( )

This method returns all the elements that match the specified CSS selector in the
document.

Syntax:

let elements = document.querySelectorAll("CSS selector");

Example:

<body>
<h1> JavaScript Query Selector</h1>
<h1 class="myClass">Class 1</h1>
<p class="myClass"> Myclass</p>
<div id="firstid">
<p> It is the div p paragraph</p>
<p class="pclass"> div p class</p>
</div>
<p id="myid"> It is p id</p>
<div id="divid"> It is div id</div>
<script>
//Element selector
var e = document.querySelectorAll ("p");
console.log(e);
</script>
</body>

11.4 JavaScript Form Validation

It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer
JavaScript form validation.

Consider the following HTML and CSS for that creates a login form:

TUM is ISO 9001:2015 Certified


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Login Page </title>
<style>
Body {
font-family: Calibri, Helvetica, sans-serif;
background-color: crimson;
}
button {
background-color: #153ce6;
width: 100%;
color: white;
padding: 15px;
margin: 10px 0px;
border: none;
border-radius: 10px 10px 10px 10px;
cursor: pointer;
}
form {
border: 3px solid #4c05cf;
margin: auto;
width: 500px;
border-radius: 25px;
}
input[type=text], input[type=password] {
width: 100%;
margin: 8px 0;
padding: 12px 20px;
display: inline-block;
border: 2px solid green;
box-sizing: border-box;
}
button:hover {
opacity: 1;
color: white;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
margin: 10px 5px;
}

TUM is ISO 9001:2015 Certified


.container {
background-color: lightblue;
box-sizing: border-box;
margin: auto;
width: 500px;
padding: 40px;
border-radius: 25px;
}
</style>
</head>
<body>
<center> <h1> Student Login Form </h1> </center>
<form name="myForm" action="/login.php" onsubmit="return validateForm()"
method="post">
<div class="container">
<label>Username : </label>
<input type="text" placeholder="Enter Username" name="username" >
<label>Password : </label>
<input type="password" placeholder="Enter Password" name="password" >
<button type="submit">Login</button>
<input type="checkbox" checked="checked"> Remember me
<button type="button" class="cancelbtn"> Cancel</button>
Forgot <a href="#"> password? </a>
</div>
</form>
</body>
</html>

TUM is ISO 9001:2015 Certified


11.4.1 Validate Empty Text Field

To validate the above form such that the username and the password are not empty,
add the following JavaScript code on the body section.

<script>
function validateForm() {
let username = document.forms["myForm"]["username"].value;
let password = document.forms["myForm"]["password"].value;
//if username is empty
if (username == "") {
alert("Username must be filled out");
return false;
}
//if password is empty
if (password == "") {
alert("Input your password");
return false;
}
}
</script>

TUM is ISO 9001:2015 Certified


11.4.2 Validate Name

To validate a name field that that the input is text only, we use the regular expression
(regEx) /^[A-Za-z]+$/. This will accept lowercase or uppercase characters but not
numerical or special characters since name can’t have such.

Example:

<!DOCTYPE html>
<html>
<body>
<script>
function validatename()
{
var name=document.myform.name.value;
var regName=/^[A-Za-z]+$/; //Javascript reGex for Name Validation.
if (name == "" || !regName.test(name)) {
window.alert("Please input alphabet characters only!.");
name.focus();
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validatename();">
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

11.4.3 Validate Email

We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

 email id must contain the @ and . character


 There must be at least one character before and after the @.
 There must be at least two characters after . (dot).

Example:

TUM is ISO 9001:2015 Certified


<!DOCTYPE html>
<html>
<body>
<script>
function validateemail()
{
var email=document.myform.email.value;
var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g; //Javascript
reGex for Email Validation.
if (email == "" || !regEmail.test(email)) {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

11.4.4 Validate Phone Number

We validate a phone number of 10 digits with no comma, no spaces, no punctuation


and there will be no + sign in front the number. Simply the validation will remove
all non-digits and permit only phone numbers with 10 digits.

Example:

<!DOCTYPE html>
<html>
<body>
<script>
function validatephone()
{
var phone=document.myform.phone.value;
var regPhone=/^\d{10}$/; //Javascript reGex for phone number Validation.

TUM is ISO 9001:2015 Certified


if (phone == "" || !regPhone.test(phone)) {
window.alert("Invalid phone number!.");
4
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validatephone();">
Phone Number: <input type="text" name="phone">
<p style="color: red;" >* Phone number should have exactly ten digits</p>
<input type="submit" value="register">
</form>
</body>
</html>

11.4.5 Validate Gender Selection

We can validate radio buttons for gender to allow users to select one gender before
submission. If the radio button is not selected, it alerts the user to select gender

Example:

<!DOCTYPE html>
<head>
<script >
function ValidateGender(form){
ErrorText= "";
if ( ( form.gender[0].checked == false ) && ( form.gender[1].checked == false ) )
{
alert ( "Please choose your Gender: Male or Female" );
return false;
}
if (ErrorText= "") { form.submit() }
}
</script>

TUM is ISO 9001:2015 Certified


</head>
<body>
<form name="myform" action="#" method=post>
Your Gender: <br>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br>
<input type="button" name="SubmitButton" value="Submit"
onClick="ValidateGender(this.form)">
<input type="reset" value="Reset">
</form>
</body>
</html>

11.4.6 Validate dropdown menu items

We can also validate a form with dropdown menu items such that it will alert the
user to select an item if not selected.

Example:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getIndex()
{
var gender=document.getElementById("mySelect")
if(!gender.selectedIndex){
alert ("Please select course to study")
return false;
}
}
</script>
</head>
<body>
<form>
Course:
<select id="mySelect" name = "select course">
<option value="">Select Course</option>

TUM is ISO 9001:2015 Certified


<option value="DICT">DICT</option>
<option value="DCS">DCS</option>
<option value="BTIT">BTIT</option>
<option value="BSIT">BSIT</option>
</select>
<p style="color: red;" >* Please select course</p>
<input type="button" onclick="getIndex()" value="Register">
</form>
</body>
</html>

11.4.7 Validate Password Match

Ensures validation of two passwords that should match during registration.

Example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.myform.firstpassword.value;
var secondpassword=document.myform.secondpassword.value;
if (firstpassword == "") {
alert("First password must be filled out");
return false;
}
if (secondpassword == "") {
alert("Second password must be filled out");
return false;
}
if(firstpassword==secondpassword){
return true;
}
else{
alert("Passwords dont match!Please enter correct passwords");
return false;

TUM is ISO 9001:2015 Certified


}
}
</script>
</head>
<body>
<form name="myform" action="#" onsubmit="return matchpass()">
Password:<input type="password" name="firstpassword" /><br/>
Re-enter Password:<input type="password" name="secondpassword"/><br/>
<input type="submit">
</form>
</body>
</html>

11.4.8 Validate Password Security

Password can be secured by validating it using a more complex regex. For example,
we ca validate it to accept at least 8 characters, have at least an uppercase letter and
lowercase letter and a special character.

Example:

<!DOCTYPE html>
<html>
<body>
<script>
function validate_pass_strength()
{
var pass=document.myform.pass.value;
var regPass=/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
//Javascript reGex for secure password Validation.
if (pass == "") {
alert("Enter password");
return false;
}

if (pass == "" || !regPass.test(pass)) {


window.alert("Invalid password.");
return false;

TUM is ISO 9001:2015 Certified


}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return
validate_pass_strength();">
Password: <input type="password" name="pass">
<p style="color: red;" >* Password should be at least 8 characters,have at least one
uppercase,one lowercase,a number and a special character</p>
<input type="submit" value="register">
</form>
</body>
</html>

11.5 Summary

JavaScript has two types of control statements. Conditional and Iterative (Looping)
with their particular uses. We learned about conditional statements like IF, IF-ELSE,
and SWITCH, along with their respective syntaxes. And for Iterative Statements, we
learned about WHILE, DO-WHILE and FOR along with syntaxes. A condition is
passed and checked until satisfied.

It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer
JavaScript form validation.

TUM is ISO 9001:2015 Certified


Exercise:
The following is a HTML code for a registration form. Below it is snapshot of the
form. Write a single JavaScript file that will validate all the fields.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
Body {
font-family: Calibri, Helvetica, sans-serif;
background-color: chocolate;
}
button {
background-color: blue;
width: 100%;
color: white;
padding: 15px;
margin: 10px 0px;
border-radius: 25%;
cursor: pointer;
}
form {
border: none;
}
input[type=text], input[type=password] {
width: 100%;
margin: 8px 0;
padding: 12px 20px;
display: inline-block;
border: 2px solid green;
box-sizing: border-box;
}
button:hover {
background-color: forestgreen;
}
.container {

background-color: lightblue;
box-sizing: border-box;
margin: auto;

TUM is ISO 9001:2015 Certified


width: 500px;
padding: 40px;
}
</style>
</head>
<body>
<form name =”form1” action=”#” onsubmit =”validate()”>
<div class="container">
<center> <h1> Student Registration Form</h1> </center>
<hr>
<label> Firstname </label>
<input type="text" name="firstname" placeholder= "Firstname" size="15" required />
<label> Lastname: </label>
<input type="text" name="lastname" placeholder="Lastname" size="15"required />
<div>
<label>
Course :
</label>

<select>
<option value="Course">Course</option>
<option value="DICT">DICT</option>
<option value="DCS">DCS</option>
<option value="BTIT">BTIT</option>
<option value="BSIT">BSIT</option>
</select>
</div>
<div>
<label>
Gender :
</label><br>
<input type="radio" value="Male" name="gender" > Male
<input type="radio" value="Female" name="gender"> Female
</div>
<label>
Phone :
</label>
<input type="text" name="phone" placeholder="phone no." size="10"/ required>

TUM is ISO 9001:2015 Certified


<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>

<label for="psw-repeat"><b>Re-type Password</b></label>


<input type="password" placeholder="Retype Password" name="psw-
repeat" required>
<button type="submit" class="registerbtn">Register</button>
</form>
</body>
</html>

TUM is ISO 9001:2015 Certified


Validation criteria:

*All fields must not be empty

* First name ad last name should accept only string characters

* Course must be selected

* Gender must be selected

* Password should be at least 8 characters, have at least one uppercase, one


lowercase, a number and a special character

* The two passwords must match

TUM is ISO 9001:2015 Certified

You might also like