0% found this document useful (0 votes)
6 views90 pages

Chapter3 JavaScript

The document outlines a syllabus for a course on web development, focusing on client-side and server-side scripting, particularly using JavaScript and PHP. It covers the basics of JavaScript, including its history, syntax, data types, and various programming concepts such as functions, loops, and conditional statements. Additionally, it provides practical examples and coding techniques for implementing JavaScript in web pages.

Uploaded by

abhisheksosa1
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)
6 views90 pages

Chapter3 JavaScript

The document outlines a syllabus for a course on web development, focusing on client-side and server-side scripting, particularly using JavaScript and PHP. It covers the basics of JavaScript, including its history, syntax, data types, and various programming concepts such as functions, loops, and conditional statements. Additionally, it provides practical examples and coding techniques for implementing JavaScript in web pages.

Uploaded by

abhisheksosa1
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

Punit A.

Lathiya
Assistant Professor
EC Department
GEC Rajkot
Syllabus : 3161012
Syllabus
How Website works?
Client side scripting
Why Use Client-side Programming?
PHP already allows us to create dynamic web pages.

Why we also use client-side scripting?


• client-side scripting (JavaScript) benefits:
▫ usability: can modify a page without having to post back
to the server (faster UI)
▫ efficiency: can make small, quick changes to page without
waiting for server
▫ event-driven: can respond to user actions like clicks and
key presses
Why Use Client-side Programming?

Why use server-side scripting?


• Server-side scripting (PHP) benefits:
▫ security: has access to server's private data; client can't
see source code
▫ compatibility: not subject to browser compatibility issues
▫ power: can write files, open connections to servers,
connect to databases, ...
Main Part of webpage
• HTML:
▫ Hyper Text Markup Language
▫ Static skeleton of web application and websites
• CSS:
▫ Cascading Style Sheets
▫ Use to handle presentation of web pages
 i.e. : Boarder, alignment, font, background etc
▫ Makes website more beautiful and modern looking
• Javascript: (JS)
▫ High-level dynamic interpreted programming
language
▫ Allows client side scripting to create dynamic webpage
Javascript (History)
• JavaScript was invented by Brendan Eich in 1995,
and became an ECMA standard in 1997.
• ECMAScript is the official name of the language.
• ECMAScript versions have been abbreviated to
ES1, ES2, ES3, ES5, and ES6.
• Since 2016 new versions are named by year
(ECMAScript 2016 / 2017 / 2018).

Reference : [Link]
Javascript
• Initially designed for making pages “alive”
• Script can be run inside browser itself.
• Can be executed on browse and server.
• It is safe language when used on browsers.
• Other language (coffee script , typescript ) get “transpired” to
Javascript.
• JavaScript and Java are different programming language.
• NOT related to Java other than by name and some syntactic
similarities
Javascript
• a lightweight programming language ("scripting language")
▫ used to make web pages interactive
▫ insert dynamic text into HTML (ex: user name)
▫ react to events (ex: page load, user click)
▫ get information about a user's computer (ex: browser type)
▫ perform calculations on user's computer (ex: form validation)
▫ a web standard (but not supported identically by all browsers)
Javascript vs Java
• interpreted, not compiled
• more relaxed syntax and rules
▫ fewer and "looser" data types
▫ variables don't need to be declared
▫ errors often silent (few exceptions)
• key construct is the function rather than the class
• contained within a web page and integrates with
its HTML/CSS content
Javascript vs Java
Java JS
Programming Language Scripting Language
Designed by Sun microsystems Designed by Netscape communication
corporation
Designed to used applets, program To improvise web page , client side
Java applets are compiled in class JS is simple text commands written in
files, can be used in web pages HTML file
Java applets visualize in webpage as JS can effect to any part of webpage
box
Object Oriented Language Object Oriented Language
VS Code Shortcuts
• Emmet Abbreviation
• Type following:
• ! ➔ Press Enter
➔ Gives basic minimal html code
• [Link] ➔ Press Enter
▫ ➔ Creates class container
<div class="container"></div>
• Button#click ➔ Press Enter
▫ ➔ Creates ID
<Button id="click"> _________ </Button>
Where to write JS .

• JavaScript code is inserted between <script> and


</script> tags
<script>
[Link]("demo").innerHTML = "My First JScript";
[Link](“Submit Successfully”);
[Link](“Data Entered”);
</script>
• JavaScript can be written
▫ within HTML code
 <head>
 <body>
▫ In separate file (with .js extension)
Where to write JS .

• JavaScript can be written in <head>


<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>JavaScript in Head</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
Where to write JS .

• JavaScript can be written in <body>


<!DOCTYPE html>
<html>
<body>
<h1>Java Script in Body </h1>
<p id="demo">A Paragraph </p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
[Link]("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>
Way to write JS
External JS :
(Separate File : [Link]))
Console API
[Link](“______________”)
[Link](“ Change line3”)
[Link](“ Error in Line 3”)
[Link]( condition)

[Link](“ Hello”) // on main HTML page


JS Identifiers
• Variables/Function name used in JS Code is known as
identifier
• Rules to declare variable in JS Code:
▫ Must be alphabets (A-Z, a-z), numbers (0-9) and
underscore (_)
▫ Space and special characters (%,#,&,!,…) Not allowed
▫ Variable name is case sensitive
 Ex: Count and count is different
▫ Length is not fixed but has to finish in one line.
▫ Must not be keywords of JS
JS Identifiers
Invalid Variable Name Valid Variable Name
Count year Total_days
1Date lastDate
console C1
Egg# Egg_Value
Total-value
T1-count
How to declare variable
• Local Variable :
▫ Declare in particular function
▫ Can not be used outside of function

• Global Variable
▫ Declared in main script
▫ Can be used in any function.
How to declare variable?
• Keyword : var , let
• DataType can be automatically defined (string ,
number, boolean etc ) as value assigned to it.
• Example:
▫ var m1 = 10
▫ var f = 20.34
▫ var s1 = “Hello”
▫ var s2 = ‘GECR’
▫ var d = null
▫ var df = undefined
▫ var sw = true
▫ var arr = [34 , 56 , 9 ]
DataTypes
• Two Types:
▫ Primitive data type :
 Undefined, null, number, string, boolean, symbol
▫ Reference/Special data type
 Arrays, Objects
Primitive Data Types
• Numbers
▫ var m1 = 10
▫ var f = 20.34
• String
▫ var s1 = “Hello”
▫ var s2 = ‘GECR’
• Boolean
▫ var a = true
▫ var b = false
• Undefined
▫ If value is not given to variable or value is undefined.
▫ var f = undefined
▫ var z2; // only declared variable is undefined
• NULL
▫ var K1 = null // different from undefined
Reference/Special Data Types
• Objects
▫ var marks = { ravi : 10 ,
ronak : 20.30,
raj : 98
};
• Arrays:
▫ var z1 = [1, 2, 34, 37, 89]
▫ var z2 = [1 , 2, “ravi”, 43, 23]
• Question:
▫ Find difference and similarity between objects and array
▫ Find where to use objects and array
Operators
• Arithmetic (+, - , *, / , %)
• Conditional / comparision ( >, >=, <, <= , ==, !=)
▫ Results in True or False
• Logical (&&, ||, !)
▫ Results in True or False
• Bitwise Operator ( &, | , ^, ~)
• Ternary Operator(?:)
▫ C = (condition)?_True_Expression_: _False_Expression_
• Assignment Operator ( = , +=, *= , -=, /=)
• Shift Operator ( << , >>)
• Increment/Decrement ( ++ , -- , Pre, Post)
Bitwise Operator
50 = 0011 0010 50 = 0011 0010
78 = 0100 1110 78 = 0100 1110
---------------------- ----------------------
& = 0000 0010 = 2 ^ = 0111 1100 = 124

50 = 0011 0010
78 = 0100 1110
----------------------
| = 0111 1110 = 126
Bitwise Operator
50 = 0011 0010
----------------------
~ = 1100 1101 = 205

51 = 0011 0011
51 1’s comp = 1100 1100
51 2’s comp = 1100 1101 = (-51) = (205)
Ternary Operator
a = 50
B = 78
c = ((a<100)||(b>50))?(a+b/2):(a+b*2)
= ( True || True) ? (a+b/2):(a+b*2)
= True ? (50 + 78/2): ________
= 50 + 78/2
= 50 + 39
= 89
Assignment Operator
Operation Shorthand notation
C=C+1 C += 1
C = c -1 C -= 1
C = C*10 C *= 10
C = C & 30 C &= 30
C = C | 30 C |= 30
C=A+B
Shift Operator
P1DIR = (1<<3) = 0000 1000
0x80 = 1000 0000
P1DIR |= (1<<3) (0x80>>2) = 0010 0000
P1DIR = P1DIR | (1<<3)

P1DIR = xxxx xxxx


or (1<<3) = 0000 1000
-----------------------------------
P1DIR = xxxx 1xxx
Increment/Decrement Operator
• C = A++ ( Post increment)
▫ Assign A into C, Then Increment A
▫ A = 50
▫ C = A++
 C = 50
 A = 51
• C = ++A (Pre increment)
▫ First increment A, then Assign A into C
▫ A = 50
▫ C = ++A
 A = 51 , C = 51
Function in JS
• function avg(a,b){
return (a+b)/2;
}

var c1 = avg(5,15)
var c2 = avg(60, 50)
If Condition
• Simple if
• if-else statement
• Ladder if-else statement
• Nested if-else statement
If Condition
if( a > 16 && a<21) if( a <= 12) {
{ [Link](“Kid”);
[Link](“Teenage”); }
} else if(a>12 && a <=21){
[Link](“Teenage”);
if( a > 16) }
{ else if(a>21 && a <=35){
[Link](“Teenage”); [Link](“Young”);
} }
else
{ else if(a>35 && a <=50){
[Link](“Kid”); [Link](“Mature”);
} }
else {
[Link](“Aged”);
}
Loop
• For Loop: • Break
▫ for • If condition satisfy,
▫ foreach stop iterating.
▫ for…in • Continue
▫ for …of • If condition satisfy,
• While Loop: that part will be
• do-while Loop: skipped
Loop (For)
var arr = [10,20,30,40];
let sum = 0;
for (var i=0; i<[Link] ; i++)
{
sum = sum + arr[i];
}
[Link](sum);

Output : 100
Loop (Foreach)
var numbers = [10,20,30,40];
let sum=0;
[Link](myfunction);
[Link](sum);

function myfunction(item)
{ sum = sum + item; } Output : 100

var numbers = [10,20,30,40];


3 Arguments :
let sum=0; item, index, array
[Link](myfunction);
[Link](numbers);

function myfunction(item, index, marr)


{ marr[index] = item*10; } Output : Array(4) [ 100, 200, 300, 400 ]
Syntax :
for (variable in array)
{ // code block to be executed }

Loop (For in) for (key in object)


{ // code block to be executed }

var arr = [10,20,30,40]; Iterable: string/array/Object


let sum = 0;
for (let x in arr)
{
sum = sum + arr[x];
}
[Link](sum); Output : 100

var marks = { Rahul : 20, Rajat : 30 , Ravi : 50};


for (let x in marks)
{
[Link](marks[x]);
} Output : 20 30 50
Syntax :
for (variable of iterable)
{ // code block to be executed }

Loop (For of) Iterable : an array/string

var arr = [10,20,30,40];


let sum = 0;
for (let x of arr)
{
sum = sum + x;
}
[Link](sum); Output : 100

var arr = [10,20,30,40];


let sum = 0;
for (let x in arr)
{
sum = sum + arr[x];
}
[Link](sum); Output : 100

Note : Object is not Iterable,


So this method can’t be applied.
Loop (While & Do_While)
var arr = [10,20,30,40]; var arr = [10,20,30,40];
let j = 0; let j = 0;
while(j<[Link]) do
{ {
[Link](arr[j]); [Link](arr[j]);
j++; j++;
} } While(j<[Link]);
Output : 10 20 30 40
Output : 10 20 30 40
var arr = [10,20,30,40];
var arr = [10,20,30,40];
let j = 100;
let j = 100;
while(j<[Link])
do
{
{
[Link](‘hello’);
[Link](‘hello’);
j++;
j++;
}
Output : No output } While(j<[Link]); Output : hello
Switch Case
Switch(expression/variable)
{
case label1: //code
break;

case label2: // code


break;
.
.
case default: // code
break;
}
Switch Case Example
<script>
var m = new Date( );
var tm = [Link]( );
switch(tm)
{
case 4 : [Link](“April”);
break;
case 7 : [Link](“July”);
break;
case default :
[Link](“Go to Hell….”);
break;

}
</script>
Math Library
[Link](M)
• M = [Link] ➔ 3.141592653589
• M = [Link](10.2) ➔ 10
• M = [Link](10.2) ➔ 11
• M = [Link](10.2) ➔ 10
• M = [Link](16) ➔ 4
• M = [Link](27) ➔ 3 (cube root)
• M= Math.log10(100) ➔ 2
Array Methods
var arr = [34, 56, 18 , “hello”, 3.5];
var a2 = [2, 3]
Use [Link]( ) to see output
[Link] ➔ 5
[Link]( ); ➔ [34, 56, 18, “hello”]
[Link](“hi”); ➔ [34, 56, 18 , “hello”, 3.5, “hi”]
[Link](); ➔ [56, 18 , “hello”, 3.5];
[Link](89); ➔ [89, 34, 56, 18 , “hello”, 3.5];
[Link]( ) ➔ "34,56,18,hello,3.5“
[Link]( ) ➔ [18, 3.5, 34, 56, "hello"]
[Link](‘*’) ➔ "34*56*18*Hello*3.5“
[Link](a2) ➔ [34, 56, 18 , “hello”, 3.5, 2, 3]
[Link]() ➔ [3.5, “hello”, 18, 56, 34]
Splice( ) ➔Adds new items
Array Methods Slice( ) ➔ slices piece of array

2 : where new element should be added


var arr = [34, 56, 18 , “hello”, 3.5]; 2 : How many elements to be removed
“Orange”, “Kiwi” : Elements to be added

[Link](2, 0 , “Orange”, “Kiwi”)


➔ [34, 56, “Orange”, “Kiwi”, 18 , “hello”, 3.5]
[Link](2, 2 , “Orange”, “Kiwi”)
➔ [34, 56, “Orange”, “Kiwi” , 3.5]
[Link](1, 1) ➔ [34, 18 , “hello”, 3.5]

X = [Link](2) ➔ X = [18 , “hello”, 3.5]


map( ) ➔ create new array by
Array Methods mapping to function
Do not change original array

var numbers = [4, 9, 16, 25];


var newArr = [Link]([Link])
[Link](newArray)
Output : Array(4) [2, 3 , 4, 5]

var numbers = [4, 9, 16, 25];


var newArr = [Link](myfunction)
[Link](newArray)

function myfunction(num)
{
return (num*10);
}
Output : Array(4) [40, 90 , 160, 250]
filter( ) ➔ create new array of
Array Methods elements if element pass the test
provided in function
Do not change original array
var numbers = [14, 19, 16, 25, 33, 10];
var above18arr = [Link](myfunction)
[Link](above18arr);

function myfunction(num)
{
if(num>18) Alternate way :
return true; function myfunction(num)
else {
return false; return (num >= 18);
} }

Output : Array(3) [19,25, 33]


Objects and its method
Adding Methods to
Object

<script>
var person {
firstname : “Punit”
lastname : “Lathiya”

fullname : function()
{ return ([Link] + “ ” + [Link]) }
};

[Link]([Link]( )) With Parenthesis


[Link]([Link])
</script> Without Parenthesis

Output : Punit Lathiya


Objects and its method
<script>
var person {
firstname : “Punit”
lastname : “Lathiya”
age : 36
};

var m1 = [Link](person)
var m2 = [Link](person)

[Link](m1)
[Link](m2)
</script>
Output : Array(3) [“firstname” ,”lastname”, “age”]
Array(3) [“Punit”, “Lathiya”, 36]
Objects and its method
<script>
function person(fname, lname, age, Xcolor, len)
{
[Link] = fname;
[Link] = lname;
[Link] = age;

[Link] = new Object( ) ;

[Link] = Xcolor;
[Link] = len;
}

var p1 = new person(“Punit”, “Lathiya”, 35 , ‘brown’, 15);


[Link](p1);
</script>
String and String Methods
var Str = "Hello we are at GECR. GECR EC Dept"

[Link] ➔ 34
[Link](“GECR”) ➔ 16
[Link](“GECR”) ➔ 22
[Link](0,3) ➔ Hel
[Link](“we”, “wii”) ➔ Hello wii ….

To See All methods :


[Link]
Date
let md = new Date( )

[Link]( )
[Link]( )
[Link]( )
[Link]( )
[Link]( )

To See All methods :

[Link]
Document Object Model (DOM)
• With the HTML DOM, JavaScript can access and
change all the elements of an HTML document.
• When a web page is loaded, the browser creates a
Document Object Model of the page.
Document Object Model (DOM)
• With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
Document Object Model (DOM)
• Objects : All HTML Elements
▫ <h1> , <p> , <form>, <table>, id , div, class
• Property: value of HTML Element (that you can get or set)
▫ innerHTML, [Link], [Link] , height, width, src etc.
• Method: Action to do (like Add/delete/modify)
▫ getElementById, getElementByTagName etc
<html>
<body>
<p id="demo"> </p>

<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
Document Object Model (DOM)
• Method to find HTML Elements:
[Link](id)
[Link](name)
[Link](name)

• Changing HTML Element Property:


[Link] = new html content
[Link] = new value
[Link] = new style
[Link](attribute, value)
Document Object Model (DOM)
Handling CSS through JS:
(Try on Console window)

[Link]('h1')
[Link]('h1')[0].[Link]= "39pt"
[Link]('h1')[0].[Link] = "red“
[Link]('h1')[0].[Link] = "Yellow“
[Link]('h1')[0].[Link] = "hidden“
[Link]('h1')[0].[Link] = "None"
Document Object Model (DOM)
• Adding or Deleting Elements:
[Link](element)
[Link](element)
[Link](element)
[Link](new, old)
[Link](text)
Document Object Model (DOM)
Let k = [Link](‘div’);

let fg = [Link](‘p’)
[Link] = “Hello Vithlani Sir”
[Link] = “blue”

k[0].appendChild(fg);

let fg2 = [Link](‘p’)


[Link] = “Hello Vithlani Sir, GEC RAJKOT”
[Link] = “red”

k[0].replaceChild(fg2, fg)
HTML/JS Events
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can
"react" on these events.
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
• Method:
▫ <element event='some JavaScript'>
HTML/JS Events
Events Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
The user moves the mouse away from an HTML
onmouseout
element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Wheel The mouse wheel rolls up or down over an element
Mousedown The mouse button is pressed over an element

Lots of other…. Visit Following website……

[Link]
HTML/JS Events Examples
<button onclick="[Link]('demo').innerHTML = Date()">The
time is?</button>

<button onclick="[Link] = Date()">The time is?</button>

<button onclick =“myFunction()">Click me.</button>

<h2 onclick="[Link]='Ooops!'">Click on this text!</h2>

<img onmouseover="bigImg(this)" onmouseout="normalImg(this)"


src="[Link]" alt="Smiley" width="32" height="32">

function bigImg(x) function normalImg(x)


{ {
[Link] = "64px"; [Link] = "32px";
[Link] = "64px"; [Link] = "32px";
} }
Regular Expression (RegEx)
• A Regular Expression (RegEx) is an object that describes a
sequence of characters used for defining a search pattern.
• Example-1: To find pattern of any five letter string starting
with “a”and ending with “s”.
▫ Pattern = /^a…s/
a = “Alias_abs”;
z = [Link](pattern);
Expression String (a) Matched? Output (z)
abs No match None
alias Match alias
/^a...s$/ abyss Match abyss
Alias No match None
An abacus No match None
Regular Expression (RegEx)
• Example-2: Find/Match the word having two characters only
in which first character must be alphabet and second
character must be number.

• chess = 'He played the King in A8 and she moved her Queen in C2.’
mypattern= /\w\d/g
[Link]([Link](mypattern))

Output : Array [ "A8", "C2" ] Syntax: /pattern/modifier

Pattern : /\w\d/  /w : character


 /d : digit
Modifier : g  Global
015 354 8787 687351 3512 8735

Regular Expression (RegEx)


• Example-3: Find/Match the 4 digit pattern from data string
• Data = ‘015 354 8787 687351 3512 8735’
mypattern= /\b\d{4}\b/g
[Link]([Link](mypattern))

Output : Array [ “8787”, “3512” , “8735” ]

Syntax: /pattern/modifier

Pattern : /\b\d{4}\b/  \b : boundary (do not start matching in middle of word)


 /d{4} : digit, 4 times
 \b : boundary (do not end matching in middle of word)

Modifier : g  Global
Regular Expression (RegEx)
• Example-3: count vowels in the string
• mystr = ‘The quick brown fox jumps over the lazy dog’
mypattern= /[AEIOUYaeiouy]/g
[Link]([Link](mypattern).length)

Output : 12

Syntax: /pattern/modifier

Pattern : /[AEIOUYaeiouy]/  [ ] : Find any characters between the brackets


Modifier : g  Global
Regular Expression (RegEx)
• /pattern/modifier Modifier
i Perform case-insensitive match
g Perform Global Match (All occurrence)
m Perform Multi-line Match

Expression
(with brackets)
[abc] Find any characters from bracket
[^abc] Find any characters NOT between brackets
[0-9] Find any digits between brackets
[^0-9] Find any digits NOT between brackets
(x|y) Find alternatives from x or y
Regular Expression (RegEx)
• /pattern/modifier
Metacharacters
\w Find word character
\W Find non-word character
\d Find Digit character
\D Find Non-Digit character
\s Find White Space
\b Find a match at the beginning/end of a word, beginning
like this: \bHI, end like this: HI\b

Lots of other…. See


[Link]
Regular Expression (RegEx)
• /pattern/modifier
Quantifier
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n
Methods
Output:
Array or None
• [Link](pattern)
let text = "The rain in SPAIN stays mainly in the plain"; Result : ain
[Link]("ain");

• [Link](string) Output:
True/False
let text = "The best things in life are free";
let pattern = /e/; Result : True
let result = [Link](text);

Output:
• [Link](pattern) Integer(Position)

let text = "Mr. Blue has a blue house";


let position = [Link](/blue/); Result : 15
• To understand with More Example:
▫ [Link]
▫ [Link]
▫ [Link]
▫ [Link]
Form validation
• It is process of checking that forms has been filled
correctly before it is processed.
• Two Methods:
▫ Server Side:
 More Secure , More time taken, but tricky to code
because it takes down client side validation
▫ Client Side (Javascript):
 Easier to do
 Avoids round-trip request to server when form has
obvious errors.
 User quickly finds out if they have missed anything or
filled wrongly (like Mobile Number, Email ID)
 Notify using alert box, disable submitting forms
Form validation Java, Perl, JS,
PHP etc.

Server
Browser Active Server-side
POST or GET Code
Form

Response Page
Validation
Validation
Request Result Validation
JavaScript
Validation Code Update

Database

Client-side Server-side
Validation Validation
Form validation
• JS provides a way to validate form’s data on client
computer before sending it to server.
• Two Function:
▫ Basic Validation:
 Check whether data filled in each field.
 Done using loop through each field in form and check
data
▫ Data Format Validation:
 Check whether entered data is in correct form and
value.
 Need to add logic test.
As appearing on the As appearing in the JavaScript
screen Document Object Model

Window window
HTML document

A form
document
A text field

A checkbox
form

text checkbox
User Performs Some Action
Such as clicking,
typing, etc.
Find Object Corresponding
To User Operation

Yes
Event Handler Execute JavaScript for
Defined? the Event Handler

true Return false


Normal Behavior for
the User Action Value

Done
Basic Validation
<html>
<head>
<title>Submit Example</title>
<script> JavaScript code in next slide

</script>
Temporary
</head> action URL for
testing
<body>
<form id="myForm" method="get" action="javascript:alert('submitted')"
onsubmit="return check(this);" >
<input type="text" name="t1" >
<input type="checkbox" name="c1" value="c1" >
<input type="submit" >
</form>

</body>
</html>
Form Validation
The alert function is built in
<script language="JavaScript"> • The alert function pops up a confirmer
box with the given text and an OK
function check(form) button.
{
if([Link] == "") • This is an example to illustrate the
{ coding technique. In good design
alert("The text field is empty."); practice, a more detailed, user-friendly
return false; message might be given.
}
The check function returns false.
if(! [Link])
{ • This tells the browser to not continue
alert("The checkbox is not checked."); with the submit.
return false;
}
return true;
}

</script>
This tests if the checkbox is checked or not.
Form Validation • The checked attribute is a Boolean.
• The ! is the NOT operator.
<script language="JavaScript"> • It is, of course, pointless to have a single
checkbox that you require to be checked
function check(form)
{ • Normally, there would be multiple
if([Link] == "") checkboxes and you would verify that at least
{ one of them is checked – or whatever you
alert("The text field is empty."); wish.
return false;
}
popup alert box and the function returns
if(! [Link]) false to indicate that the submit should
{ not occur.
alert("The checkbox is not checked.");
return false;
} The check function returns true if
return true; everything is OK. This causes the submit
} to actually occur.

</script>
Email ID Validating
• Validating email is a very important point while
validating an HTML form.
• An email is a string (a subset of ASCII characters)
separated into two parts by @ symbol.
• Personal_info@domain_name
• Max : 64 character @ 256 characters
• Personal Info:
▫ Alphabets (A-Z, a-z) and Digits (0-9)
▫ Special Characters : !, #,$,%,^, fullstop(.) , {, }, +
▫ Period(Fullstop) must not be last characters
• Domain:
▫ com, org, in, edu etc
Email ID Validating
• Example of valid email id
▫ mysite@[Link]
▫ [Link]@[Link]
▫ mysite@[Link]

• Example of invalid email id


▫ [Link] [@ is not present]
▫ mysite@.[Link] [ tld (Top Level domain) can not start with dot "." ]
▫ @[Link] [ No character before @ ]
▫ mysite123@gmail.b [ ".b" is not a valid tld ]
▫ mysite@.[Link] [ tld can not start with dot "." ]
▫ .mysite@[Link] [ an email should not be start with "." ]
▫ mysite()*@[Link] [ here the regular expression only allows
character, digit, underscore, and dash ]
▫ mysite..1234@[Link] [double dots are not allowed]
var mailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;

Email ID Validating
function ValidateEmail(inputText)
{
// var mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
// varmailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;

var mailformat = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";

if([Link](mailformat))
{
alert("Valid email address!");
[Link]();
return true;
}
else
{
alert("You have entered an invalid email address!");
[Link]();
return false;
}
}
Meaning of pattern
"^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$

Pattern Meaning
^[\\w-_\.] ^ : Check
\\w : word starting with A-Z,a-z,0-9
It can also be
Underscore(_), Hyphen(-) , period(.)
*[\\w-_\.] * : Next series of characters
Same as above
\@[\\w]\.+ Next section begins with @
Following with word (\\w) and atleast
one period/dot (.)
[\\w] +[\\w]$ Some word (\\w) after dot(.)
Last part checks : Last character is
word.
Validating Phone Number
• Checking 10 digit Mobile number without
comma, punctuation mark and no + sign in front.
• Ex : 9999874585
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;

if(([Link](phoneno))
return true;
else
{
alert(“Wrong Mobile Number");
return false;
}
}
function phonenumber(inputtxt) { var phoneno = /^\d{10}$/; if(([Link](phoneno)) { return true; } else { alert("message"); return false; } }

Validating Phone Number


• Checking 10 digit Mobile number with punctuation
mark or dot
• Ex : 999-987-4585 or 999 987 4585
function phonenumber(inputtxt)
{
var phoneno = “^ \(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4}) $”;

if(([Link](phoneno))
return true;
else
{
alert("message");
return false;
}
}
if([Link] != 10 || isNaN([Link].
value) || [Link] == "")
{
[Link]("incoreect input")
check = false;
}
else
{
[Link]("correct mobile number")
check = true;
}
return check;*/
Exercise
• Validate IP Address
▫ [Link]
▫ [Link]
• Validate Entered Password
▫ Only 8-17 characters, At least one special characters
▫ No white space

▫ 1-255
Thank You

You might also like