0% found this document useful (0 votes)
56 views78 pages

Chapter 4 IP

Uploaded by

tsion
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)
56 views78 pages

Chapter 4 IP

Uploaded by

tsion
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

1

CHAPTER FOUR
JavaScript

Mulugeta G..
2

Contents

JavaScript Basics

Variables, Expression, Operators …

JavaScript Control Structures

Handling Events and Exception

JavaScript Functions

JavaScript Form Validation


3

JavaScript
• Growth of the WWW has resulted in a demand for dynamic and

interactive web sites.


• JavaScript

• is a front-end scripting language developed by Netscape for

dynamic content
• is a lightweight, interpreted programming language of the Web.

• can be used as object-oriented language

• Client-side technology

• Embedded in your HTML page

• Interpreted by the Web browser

• Simple and flexible


4

JavaScript
Advantages of JavaScript
• JavaScript allows interactivity such as:
• Implementing form validation

• Enhancing user interactions

• React to user actions, e.g. handle keys

• Sections of a page appearing and disappearing

• Content loading and changing dynamically

• Performing complex calculations

• Custom HTML controls, e.g. scrollable table

• Implementing AJAX functionality


5

JavaScript
Why JavaScript
• A web document can consist of up to three layers

• Content--> HTML
• Presentation--> CSS
• Behavior--> JavaScript
6

JavaScript
Content Layer
• content layer is always present

• It contains the information the author wishes to convey to

his or her audience, and is embedded within HTML or


XHTML markup that defines its structure and semantics
• Most of the content on the Web today is text, but content can

also be provided through images, animations, sound, video,


and whatever else an author wants to publish.
7

JavaScript
Presentation Layer
• defines how the content will appear to a human being who

accesses the document in one way or another


• The conventional way to view a web page is with a regular web

browser
• Example: content can also be converted to synthetic
speech for users who have impaired vision or reading
difficulties.
8

JavaScript
Behavior Layer
• The behavior layer involves real-time user interaction with

the document
• This task is normally handled by JavaScript

• The interaction can be anything from a validation that ensures

a required field is filled in before an order form can be


submitted,
• To sophisticated web applications that work much like

ordinary desktop programs


9

Where to Place JavaScript Code


• The JavaScript code can be placed in:

• <script> tag in the head

• <script> tag in the body – at the bottom improves display speed

• External files, linked via <script> tag in the head

• Files usually have .js extension


<script src="scripts.js" type="text/javscript">
<!– code placed here will not be executed! -->
</script>
• Highly recommended
A separate file
• The .js files get cached by the browser
10

Attributes of External JavaScript


• src – specifies the location of an external script
• type – specifies the scripting language of the script
• language – specifies the scripting language of the script
• type and language have a similar function

<script language=“JavaScript”
src=“your_source_file.js”></script>
Advantages of external JavaScript
• It separates HTML and code
• It makes HTML and JavaScript easier to read and maintain
• Cached JavaScript files can speed up page loads
11

JavaScript
Tells where the JavaScript starts
<html>
<body>
<script type=“text/javascript”>
document.write(“Hello World!”);
</script>
</body> Commands for writing output to a page
</html>

Tells where the JavaScript ends

This code produce the output on an HTML page:


Hello World!
12

Example
<html><head></head>
<body>
<script type="text/javascript">
alert('Hello JavaScript!');
</script>
</body>
</html>
<html><head></head>
<body>
<script type="text/javascript">
document.write('JavaScript rulez!');
</script>
</body>
</html>
13

Example
<html>
<html> <head>
<head> <script type="text/javascript">
function test (message) {
<script src="xyz.js"> alert(message);
</script> }
</head> A separate file </script>
</head>
<body> <body>
</body> <img src="logo.gif"
</html> onclick="test('clicked!')" />
</body>
</html>
14

Methods/Popup boxes
Using alert() Method
• It is the easiest methods to use amongst alert(), prompt() and
confirm().
• You can use it to display textual information to the user
(simple and concise).
• The user can simply click “OK” button to close it.

<head>
<script language=“JavaScript”>
alert(“An alert triggered by JavaScript”);
</script>
</head>
15

Methods/Popup boxes
Using confirm() Method
• This box is used to give the user a choice either OK or
Cancel button.
• It is very similar to the “alert()” method.
• Used if you want the user to verify or accept something.
.
<head>
<script language=“JavaScript”>
confirm(“Are you happy with the class?”);
</script>
</head>
16

Methods/Popup boxes
Using prompt() Method
• This is the only one that allows the user to type in his own

response to the specific question.

• You can give a default value to avoid displaying “undefined”.

<head> prompt ("enter amount", 10);


<script language=“JavaScript”>
prompt(“what is your ID No?”);
prompt(“what is your Name ?”);
</script>
</head>
17

Example
<script language="JavaScript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
18

JavaScript Syntax
• The JavaScript syntax is similar to C# and Java

• Variables (type-less)

• Operators (+, *, =, !=, &&, ++, …)

• Comments

• Conditional statements (if, else)

• Loops (for, while)

• Arrays (my_array[]) and associative arrays (my_array['abc'])

• Functions (can return value)


19

Variables
• Variables
• are containers for Storing Data
• JavaScript allows you to declare and use variables to store values
• How to assign a name to a variable?

• Names can contain letters, digits, underscores, and dollar


signs.
• Must begin with a letter, $ and _

• No space and punctuation characters

• JavaScript is Case-sensitive

• No reserved words or keywords


20

Variables
Scope of Variables
• When you use a variable in a JavaScript program that uses functions.
• Global variable is one that is declared outside a function and is
accessible in any part of your program
• Local variable is declared inside a function and stops existing
when the function ends
Example:
• Legal Variables: My_variable, $my_variable,_my_variable
• Illegal Variables: 1my_example, @my_variable,
#my_variable, ~my_variable
21

Variable Declaration
• JS uses the keywords var, let and const to declare variables.
• Example: let x;
x = 6;
<head>
<script language=“JavaScript”>
var id;
id = prompt(“What is your student id number?”);
alert(id);
name = prompt(“What is your name?", "No name”);
alert(name);
</script>
</head>
22

Data types
• JavaScript allows the same variable to contain different types of data values

• Primitive data types

• Number: integer & floating-point numbers

• Boolean: logical values “true” or “false”

• String: a sequence of alphanumeric characters

• Composite data types (or Complex data types)

• Object: a named collection of data

• Array: a sequence of values

• Special data types

• Null: an initial value is assigned

• Undefined: the variable has been created by not yet assigned a value
23

Strings
• Strings can store a sequence of alphanumeric characters, spaces and

special characters
• enclosed in single (‘) or in double quotation marks (“)

• What is the data type of “100”? String but not number type
<head>
<script language=“JavaScript”>
document.write(“This is a string.”);
document.write(“This string contains ‘quote’.”);
var myString = “My testing string”;
alert(myString);
</script>
</head>
24

Object
• Object anything in the real world
• E.g. (cars, dogs, money, books, … )
• In web browser, objects are browser window itself, forms, buttons,
text boxes, …
• Methods are things that objects can do.

• Cars can move, dogs can bark


• Window object can alert the user “alert()”
• All objects have properties

• Cars have wheels, dogs have hair


• Browser has a name and version number
25

Array
• Array

• contains a set of data represented by a single variable name

• Syntax:
• Arrays in JavaScript are represented by the Array Object, we need to

“new Array()” to construct this object


• Syntax: const array_name=new Array();

• first element of the array is “Array[0]” until the last one Array[i-1].

• E.g. myArray = new Array(5)

• We have myArray[0,1,2,3,4].
26

Array
• Declaring new empty array:
var arr = new Array();
• Declaring an array holding few elements:
var arr = [1, 2, 3, 4, 5];
• Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
• Reading the number of elements (array length):
arr.length;
• Finding element's index in the array:
arr.indexOf(1);
27

Example
• You can also declare arrays with variable length.
• arrayName = new Array();
• Length = 0, allows automatic extension of the length.
• Car[9] = “Ford”; Car[99] = “Honda”;
<script language=“JavaScript”>
Car = new Array(3);
Car[0] = “Ford”;
Car[1] = “Toyota”;
Car[2] = “Honda”;
document.write(Car[0] + “<br>”);
document.write(Car[1] + “<br>”);
document.write(Car[2] + “<br>”);
</script>
28

Null and Undefined


• An “undefined” value is returned when you attempt to use a

variable that has not been defined or you have declared but you
forgot to provide with a value
• Null refers to “nothing”

• You can declare and define a variable as “null” if you want

absolutely nothing in it, but you just don’t want it to be


“undefined”.
29

Example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“JavaScript”>
var test1, test2 = null;
alert(“No value assigned to the variable” + test1);
alert(“A null value was assigned” + test2);
</script>
</head>
<body> … </body>
</html>
30

Expressions
• It is a set of literals, variables, operators that merge and evaluate

to a single value

• Left_operand operator right_operand

• By using different operators, you can create the following

expressions.

• Arithmetic, logical

• String and conditional expressions.


31

Operators
• Arithmetic operators

• Logical operators

• Comparison operators

• String operators

• Bit-wise operators

• Assignment operators

• Conditional operators
32

Unary operators
• Unary type operators take only one operand

• Which one add value first, and then assign value to the variable?

Name Example

Post Incrementing operator Counter++

Post Decrementing operator Counter--

Pre Incrementing operator ++counter

Pre Decrementing operator --counter


33

Logical operators
• Used to perform Boolean operations on Boolean operands

Operator Name Description Example

&& Logical and Evaluate to “true” when both 3>2 && 5<2
operands are true

|| Logical or Evaluate to “true when either 3>1 || 2>5


operand is true

! Logical not Evaluate to “true” when the 5 != 3


operand is false
34

Comparison Operators
• Used to compare two numerical values
Operator Name Description Example
== Equal Perform type conversion before checking the “5” == 5
equality

=== Strictly equal No type conversion before testing “5” === 5


!= Not equal “true” when both operands are not equal 4 != 2
!== Strictly not equal No type conversion before testing nonequality 5 !== “5”
> Greater than “true” if left operand is greater than right operand 2>5

< Less than “true” if left operand is less than right operand 3<5

>= Greater than or “true” if left operand is greater than or equal to the 5 >= 2
equal right operand

<= Less than or equal “true” if left operand is less than or equal to the right 5 <= 2
operand
35

String Operators
• JavaScript only supports one string operator for joining two
strings.
Operator Name Description Return
value
+ String Joins two strings “HelloWorld
concatenation ”

<script language=“JavaScript”>
var myString = “”;
myString = “Hello” + “World”;
alert(myString);
</script>
36

Example
• The + operator joins strings

string1 = "fat ";


string2 = "cats";
alert(string1 + string2); // fat cats

• What is "9" + 9?
alert("9" + 9); // 99

• Converting string to number:

alert(parseInt("9") + 9); // 18
37

Assignment Operators
• Used to assign values to variables

Operator Description Example


= Assigns the value of the right operand to the left operand A=2
+= Add the operands and assigns the result to the left operand A += 5

-= Subtracts the operands and assigns the result to the left A -= 5


operand
*= Multiplies the operands and assigns the result to the left A *= 5
operand
/= Divides the left operands by the right operand and assigns A /= 5
the result to the left operand
%= Assigns the remainder to the left operand A %= 2
38

JavaScript Comments
• JavaScript comments can be used to explain JavaScript code, and to make it
more readable.
• JavaScript comments can also be used to prevent execution, when testing
alternative code.
• Comments are ignored, and will not be executed

• Single Line Comments: start with //.

• Multi-line Comments: start with /* and end with */.

• Code after double slashes // or between /* and */ is treated as a comment.

• Example:

• let x = 5; // I will be executed

• // x = 6; I will NOT be executed


39

Thank You

LAB 1: LET’S PRACTICE


JavaScript Methods, Variables and Operators
40

Conditional Statements
• Conditional statements are used to perform different actions

based on different conditions.


• In JavaScript we have the following conditional statements:
• Use if to specify a block of code to be executed, if a specified
condition is true
• Use else to specify a block of code to be executed, if the same
condition is false
• Use else if to specify a new condition to test, if the first
condition is false
• Use switch to specify many alternative blocks of code to be
executed
41

If statement
• Use the if statement to specify a block of JavaScript code to be
executed if a condition is true
• Syntax:
if (condition)
{
block of code to be executed if the condition is true
}

• NB: if is in lowercase letters. Uppercase letters of If, IF will


generate JavaScript error.
• Example: i f ( h o u r < 6 )
{
greeting=“good morning”;
}
42

else statement
• Use the else statement to specify a block of code to be executed
if the condition is false.
• Syntax:
if (condition) {
block of code to be executed if the condition is true
}
else {
block of code to be executed if the condition is false
}
• Example: if (hour<6){
greeting=“good morning”;
}
else{
greeting=“good afternoon”;
}
43

else if statement
• Use the else if statement to specify a new condition if the first
condition is false.
• Syntax:

if (condition1)
{
block of code to be executed if the condition1 is true
}
else if(condition2)
{
block of code to be executed if the condition2 is true
}
else{
block of code to be executed if both of the conditions are false
}
44

else if statement
• Example: If time is less than 6:00, create a "Good morning"

greeting, if not, but time is less than 12:00, create a "Good


afternoon" greeting, otherwise a "Good evening":

if (hour<6){
greeting=“good morning”;
}
else if(hour<12{
greeting=“good afternoon”;
}
else{
greeting=“good evening”;
}
45

switch statement
• Use the switch statement to select one of many blocks of code
to be executed..
• Syntax:
switch(expression){
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
NB: The default specifies the code to run if there is no case match.
46

switch statement
This is how it works:
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each
case.
• If there is a match, the associated block of code is executed.
case 3:
Example: day = "Wednesday";
switch (new Date().getDay()) { break;
case 0: case 4:
day = "Sunday"; day = "Thursday";
break; break;
case 1: case 5:
day = "Monday"; day = "Friday";
break; break;
case 2: case 6:
day = "Tuesday"; day = "Saturday";
break; break;
}
47

Loop/iteration statement

• JavaScript supports different kinds of loops:

• for - loops through a block of code a number of times

• for/in - loops through the properties of an object

• while - loops through a block of code while a specified

condition is true

• do/while - also loops through a block of code while a

specified condition is true


48

For loop
• Loops can execute a block of code a number of times
• Syntax:

for (statement 1; statement 2; statement 3)


{
block of code to be executed
}
• Statement 1: to initiate the variable used in the loop (i = 0).
• Statement 2: used to evaluate the condition of the initial
variable
• Statement 3 : increases/decrease the initial variable
for (i=0; i<5; i++)
{
• Example:
text +=“The number is ”+ i+ ”< br>”;
}
49

For/in loop
• The JavaScript for/in statement loops through the properties of

an object.
for (counter-variable in Object) {
• Syntax: statements;
}
• Example:

var person = {fname:“Dawit", lname:“Kebede", age:25};

var text = "";


var x;
for (x in person)
{
text += person[x];
}
50

while loop
• Execute a block of code as long as a specified condition is
true.
• Syntax:
while (condition)
{
block of code to be executed if the condition is true
Increment/decrement statement;
}

• Example:
while (i < 10)
{
text += "The number is " + i;
i++;
}
51

Do…while loop
• This loop will execute the code block once, before checking the
condition, then it will repeat the loop as long as the condition is
true.
• Syntax: do{
block of code to be executed
Increment/decrement statement;
}
while (condition);
• Example:
do{
text += "The number is " + i;
i++;
}
while(i<10);
52

Exercises
• For loop
• Write a JavaScript program to count up from 1 -->10
• Write a JavaScript program to count down from 10 -->1
• For/in loop
• Write a JavaScript program to display student information
• Write a JavaScript program to display 4 Ethiopian languages
• While loop
• Write a JavaScript program to count up from 1 -->10
• Write a JavaScript program to count down from 10 -->1
• Do-while loop
• Write a JavaScript program to count up from 1 -->10
• Write a JavaScript program to count down from 10 -->1
53

Functions
• A function is a block of organized reusable code (a set of

statements) for performing a single or related action.


• Begins with keyword “function” and the function-name and “( )”

• Inside the parentheses

• We can pass parameters to the function


• Function Declaration Syntax
• declared using the function reserved word (keyword)
function function-name(arg1, arg2) {…}
• Two types of functions: Built-in and user-defined functions
54

Built-in functions
• Functions provided by the language and you cannot change
them to suit your needs.
• Some of the built-in functions in JavaScript are shown here:
• eval - eval(expr)
• eval evaluates the expression or statements
• isFinite
• Determines if a number is finite
• isNaN
• Determines whether a value is “Not a Number”
• parseInt
• Converts string literals to integers, no number → NaN.
• parseFloat
• Finds a floating-point value at the beginning of a string.
55

User-defined functions
• For some functionality, you cannot achieve by only using the
built-in functions.
• You can define your own function as follows

• Syntax: function function_name (parameters)


{
// code segments;
}
function square(x)
• Example:
{
return (x * x);
}
56

Exercises

• Write a JavaScript program to display “Hello World”

information using function without arguments.


• Write a JavaScript program to calculate the cube of a number

using function
• Write a JavaScript program to convert Celsius into

Fahrenheit using function Hint: Celsius = 5/9*(fahrenheit-32)


• Write a JavaScript program that adds two numbers given

from the user using function. (based on this try to perform


simple calculator)
57

LAB 2: LET’S PRACTICE


JavaScript Control Statements, Functions
58

Events
• are actions that occur as a result of browser activities or user
interactions with the web pages, such as
• user performs an action (mouse click or enters data)
• validate the data entered by a user in a web form
• Communicate with Java applets and browser plug-ins
• Event categories
• Keyboard and mouse events
• Load events
• Form-related events
• onFocus() refers to placing the cursor into the text
input in the form.
• Others
• Errors, window resizing.
59

HTML HTML JavaScript Description


defined events
e
elements tags
Link <a> click Mouse is clicked on a link
dblClick Mouse is double-clicked on a link
mouseDown Mouse button is pressed
mouseUp Mouse button is released
mouseOver Mouse is moved over a link
Image <img> load Image is loaded into a browser
abort Image loading is abandoned
error An error occurs during the image loading

Area <area> mouseOver mouse is moved over an image map area


mouseOut mouse is moved from image map to
dblClick outside
mouse is double-clicked on an image map

Form <form> submit user submits a form


Reset user refreshes a form
60

Event handlers

• When an event occurs, a code segment is executed in response

to a specific event is called “event handler”


• Event handler names are quite similar to the name of events

they handle
• Example:

• event handler for the “click” event is “onClick”.

• <HTMLtag eventhandler=“JavaScript Code”>


61

Event Triggered when


Handlers
onChange The value of the text field, textarea, or a drop
down list is modified
onClick link, an image or a form element is clicked once
onDblClick The element is double-clicked
onMouseDown The user presses the mouse button
onLoad A document or an image is loaded
onSubmit A user submits a form
onReset The form is reset
onUnLoad The user closes a document or a frame
onResize A form is resized by the user
62

onClick event handlers


<html>
<head><title>onClick Event Handler Example</title>
<script language=“JavaScript”>
function warnUser(){
return confirm(“CS students?”);
}
</script>
</head>
<body>
<a href=“reference.html”, onClick=“return warnUser();”>CS Students
access only</a>
</body>
</html>
63

onLoad event handlers

<html>
<head>
<title>onLoad and onUnload Event Handler </title>
</head>
<body onLoad=“alert(‘Welcome User’);”
onUnload=“alert(‘Thanks for visiting the page’);”>
Load and UnLoad event test.
</body>
</html>
64

User events form example


<html><head>
<title>Simple JavaScript Button</title>
<script language=“JavaScript">
function dontClick() {
alert("I told you not to click!");
}
</script>
</head>
<body>
<h1>Simple JavaScript Button</h1>
<form>
<input type=“button“
value="Don't Click Me"
onClick="dontClick()">
</form></body></html>
65

JavaScript Form Validation


• JavaScript can be used to validate data in HTML forms before

sending off the content to a server.

• Data validation is the process of ensuring the user input is

clean, correct, and useful.

• Typical validation tasks are:

• has the user filled in all required fields?

• has the user entered a valid date?

• has the user entered text in a numeric field?


66

JavaScript Form Validation


• Most often, the purpose of data validation is to ensure correct

user input.

• Validation can be defined by many different methods, and

deployed in many different ways.

1. Server side validation is performed by a web server, after


input has been sent to the server.

2. Client side validation is performed by a web browser, before


input is sent to a web server.
67

JavaScript Form Element


• HTML forms can include eight types of input elements

• Text fields, Textarea fields

• Radio buttons

• Check box buttons

• Hidden fields

• Password fields

• Combo box select menu

• List select menu

• Each object has its own properties and methods.


68

Example
<head>
<script LANGUAGE="JavaScript">
function checkForm( )
{
if (document.mainForm.firstName.value == "") {
alert("Please type in your first name!");
}
}
</script>
</head>
<h3> Form Validation</h3>
<form name="mainForm" onsubmit="return checkForm()">
Name: <input type="text" name="firstName" />
<p><input type="submit" value="Submit"></p>
</form>
69

Form Validation Script


<html><head>
<title>Form Example</title>
<script LANGUAGE="JavaScript">
function validate() { <body>
if (form1.yourname.value.length < 1) {
alert("Please enter your full name."); <h1>Form Validation Example</h1>
return false;
}
<form name="form1" enctype="text/plain“
if (document.form1.address.value.length < onSubmit="validate();">
3) {
alert("Please enter your address.");
<p><b>Name:</b> <input type=“text"
return false; length="20" name="yourname"></p>
} <p><b>Address:</b> <input type=“text"
if (document.form1.phone.value.length < 3)
{ length="30" name="address"></p>
alert("Please enter your phone <p><b>Phone: </b> <input type=“text"
number.");
return false; length="15" name="phone"></p>
} <p><input type=“submit" value="Submit"></p>
return true;
} </form>
</script> </body>
</head>
</html>
70

Checking Form Values Individually Example


<html><head><title>On-Line Training</title>
<script language=“JavaScript">
<!--
// When the user changes and leaves textfield, check
// that a valid choice was entered. If not, alert
// user, clear field, and set focus back there.
function checkLanguage() {
// or document.forms["langForm"].elements["langField"]
var field = document.langForm.langField;
var lang = field.value;
var prefix = lang.substring(0, 4).toUpperCase();
if (prefix != "JAVA") {
alert("Sorry, '" + lang + "' is not valid.\n" +
"Please try again.");
field.value = ""; // Erase old value
field.focus(); // Give keyboard focus
}
}
71

// -->
</script></head>
<body><h1>On-Line Training</h1>
<form action="cgi-bin/registerLanguage" name="langForm">
To see an introduction to any of our on-line training
courses, please enter the name of an important Web
programming language below.
<p>
<b>Language:</b>
<input type=“text" name="langField"
onFocus="describeLanguage()" onBlur="clearStatus()"
onChange="checkLanguage()">
<p>
<input type=“submit" value="Show It To Me">
</form>
</body></html>
72

Result
73

Example: 2
<html>
<head>
<script type="text/javascript">
// Form validation code will come here.
function validate() <body >
{ <form method='post' name="Form1"
if( document.Form1.username.value == "" ) onsubmit="return(validate())"; >
{ <fieldset>
alert( "Please provide your username!" ); <legend> <b>Login form</b></legend>
document.Form1.username.focus() ; Username:
return false; <input type="text" name="username"
} maxlength="50" size="25"><br><br>
if( document.Form1.password.value == "" ) Password:
{ <input type="password" name="password"
alert( "Please provide your password!" ); maxlength="50" size="25"><br/><br>
document.Form1.password.focus() ; <input type='submit' value="login" /><input
return false; type='reset' value='Reset' />
} </fieldset>
} </form>
</script> </body>
</head>
</html>
74

Example 3: E-mail Validation


<html> if(y=="")
<head>
<script type="text/javaScript">
{
function validateForm() alert("please provide your
{ passwerd");
var x=document.myForm.email.value;
var y=document.myForm.pass.value; document.myForm.pass.focus(
var atpos=x.indexOf("@");
);
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || return false;
dotpos+2>=x.length) }
{
alert("Not a valid e-mail address"); }
document.myForm.email.focus(); </script>
return false; </head>
}
75

Example 3: E-mail Validation


<body>
<form name="myForm" onsubmit="return
validateForm();" method="post">
<fieldset>
<legend>Sign In</legend>
Email:&nbsp; &nbsp;
<input type="text" name="email"><br/>
Password: <input type="password"
name="pass"><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
76

JavaScript Form Validation


• var letters = /^[A-Za-z]+$/;

• var numbers = /^[0-9]+$/;

• var letterNumber = /^[0-9a-zA-Z]+$/;

• var decimal= /^[-+]?[0-9]+\.[0-9]+$/;

• var email= /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

• var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-

]\d{4}$/;

• var phoneno = /^\+?([0-9]{3})\)?[-. ]?([0-9]{5})[-. ]?([0-9]{4})$/;

• var phoneno = /^\d{10}$/;


77

Automatic Form Validation

• HTML form validation can be performed automatically by

the browser.

• If a form field (fname) is empty, the required attribute prevents

this form from being submitted:

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
78

?
END OF CHAPTER FOUR
Next: Chapter Five – PHP

You might also like