Session Eleven - Javascript Control Structures and Form Validation
Session Eleven - Javascript Control Structures and Form Validation
11.1 Introduction
We ca also use JavaScript to validate user input on a form such as looking for empty
fields, email validation , password validation etc.
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>
Syntax:
if (condition)
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>
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;
It includes three important parts: Loop Initialization, Test Condition and Iteration
Syntax:
Example:
<body >
<script type="text/javascript">
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>
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;
DOM means Document Object Model. DOM Selectors, as the name suggests is used to select
HTML elements within a document using JavaScript.
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:
Parameters:
elements is a collection of all the found elements in the order they appear with
the given tag name.
Example:
<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 =
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>
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.
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
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";
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.
The trim() method removes whitespace from both ends of a string and returns a new
string, without modifying the original string.
This method returns all the elements that match the specified CSS selector in the
document.
Syntax:
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>
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:
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>
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>
There are many criteria that need to be follow to validate the email id such as:
Example:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
function validatephone()
{
var phone=document.myform.phone.value;
var regPhone=/^\d{10}$/; //Javascript reGex for phone number Validation.
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>
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>
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;
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;
}
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.
<!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;
<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>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>