You are on page 1of 66

Lecture 12: Regular expressions and

validate Form in JavaScript


Objectives
• Validate data in form
• How to use regular expressions
• How to handle exceptions
• The register application
Validate data in form
SET STYLES FOR ELEMENTS

 You can set styles for components using


 ID
 Card
 Class

4
SET STYLES FOR ELEMENTS ID

 Implementation steps
 Step 1. Use ID to access elements
 Step 2. Use the style attribute to set the style for that
element

var hTieuDe = document.getElementById("hTieuDe");


hTieuDe.style.fontFamily = "arial"

5
DEMO

Xem CSS
6
DEMO
<html >
<head>
<script type="text/javascript">
function xanhButtonClick() {
var pText = document.getElementById("pText");
pText.style.color = "blue";
}
function doButtonClick() {
var pText = document.getElementById("pText");
pText.style.color = "red";
}
</script>
</head>
<body>
<p id="pText">Thiet lap style bang ID</p>
<button onclick="xanhButtonClick();">Xanh</button>
<button onclick="doButtonClick();">Do</button>
</body>
</html>
7
SETS THE STYLE FOR A GROUP OF
ELEMENTS
 The problem arises:
 Want to change styles for multiple elements
<p id = "pText">Thiet lap style cho nhieu thanh phan</p>
<p id = "p1">Thanh phan 1</p>
<p id = "p2">Thanh phan 2</p>
<p id = "p3">Thanh phan 3</p>
 Solution:
 Use the getElementsByName or
getElementsByTagName method to get a group of
elements
 Use For loop to iterate over elements
var pAr = document.getElementsByTagName("p");
for (var i = 0; i < pAr.length; i++) {
pAr[i].style.color = "blue";
}
8
IMAGE ROLLOVER

 Image Rollover is the effect of changing the


image when hovering over the image

9
ROLLOVER

 Achieve this effect by handling the


onMouseOver and onMouseOut events for the
img tag
 onMouseOver: event triggered when the user hovers
over the image
 onMouseOut: event is triggered when the user moves
the mouse outside the image

10
DEMO ROLLOVER

<html>
<head>
<script type="text/javascript">
function onMouseOverEvent() {
document.img_hoa.src = "hoaover.jpg";
}
function onMouseOutEvent() {
document.img_hoa.src = "hoaout.jpg"; Truy cập đến phần
} tử bằng attribute
</script> name
</head><body>
<img name="img_hoa" src="hoaout.jpg"
onmouseover="onMouseOverEvent();"
onmouseout="onMouseOutEvent();" />
</body>
</html>

11
THE PROBLEM ARISES WHEN PERFORMING
ROLLOVER
 Problem: The first time you hover over an image, it
takes a while for the image to load even though the
page has been open for a long time.
 Cause: When the user hovers over the mouse, the
new image is loaded
 Solution: Load the image first
 Technique:
 Create an image object for each image you want to load first
 Assign the path of the image to the src attribute of that image
object
 Explain:
 When encountering the command
imageObject.src=“link_cua_anh”, the image is loaded
underground, the computer continues to execute the commands
after this command.
 This solution does not make website loading slow
13
DEMO LOAD IMAGE
<html><head>
<script type="text/javascript">
var hoaover = new Image();
var hoaout = new Image();
function loadAnh() {
hoaover.src = "hoaover.jpg";
hoaout.src = "hoaout.jpg";
}
function onMouseOverEvent() {
document.img_hoa.src = hoaover.src
}
function onMouseOutEvent() {
document.img_hoa.src = hoaout.src
}
</script></head>
<body onload = "loadAnh();">
<img name="img_hoa" src="hoaout.jpg"
onmouseover="onMouseOverEvent();"
onmouseout="onMouseOutEvent();" />
</body></html>

14
SLIDE SHOW

 What is Slide Show?


 This is an image effect that appears instead of the
previous image
 There may be a control bar for the user

Thanh điều khiển

15
SLIDE SHOW

 Steps to make Slide Show


 Preload all images
 Event handling for the Next button
 Event handling for the Back button

<body onload = "loadAnh();">


<img id="hoa" src="anh0.jpg" />
<input type="button" value="back" onclick="back();" />
<input type="button" value = "next" onclick="next();"/>
</body>

16
DEMO
var anhAr = [];
var currentIndex=0;
function loadAnh() {
for (var i = 0; i < 6; i++) {
anhAr[i] = new Image();
anhAr[i].src = "anh"+i+".jpg";
}
}
function next() {
if (currentIndex < 4) {
currentIndex++;
document.getElementById("hoa").src = anhAr[currentIndex].src;
}
}
function back() {
if (currentIndex > 0) {
currentIndex--;
document.getElementById("hoa").src = anhAr[currentIndex].src;
}
}

17
DEMO

Ảnh được thay đổi


sau khi nhấn Next

19
Validate data in form
Data validation is the process of ensuring that computer 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?
 Data validation is to ensure correct input to a computer application.
 Deployed in many different ways.
 Server side validation is performed by a web server, after input has
been sent to the server.
 Client side validation is performed by a web browser, before input is
sent to a web server.
Example: check form field is empty

Can use required attribute


CONTROLS

 JavaScript provides controls for user interaction


 Select Box
 CheckBox
 Radio Button
 Form

22
ATTRIBUTE NAME

 Some elements are defined with a name attribute


(for example, checkbox controls, radio buttons,
etc.)
 You can use the attribute name to access a group
of elements with the same attribute name value
 Distinguish between id and name
 id is unique, each id represents 1 element
 Multiple elements have the same attribute name value,
each name value represents a group of elements
 Use the getElementsByName(name) method to get
an array of elements with the same name attribute

23
DEMO USES ATTRIBUTE NAME TO ACCESS A
GROUP OF ELEMENTS
<html>
<body >
<input type="checkbox" name="test" value="how"/>
<input type="checkbox" name="test" value="are"/>
<input type="checkbox" name="test" value="you"/>
<input type="checkbox" name="test" value="?"/>
<script type="text/javascript">
var ckAr = document.getElementsByName("test");
var str = "";
for (var i = 0; i < ckAr.length; i++) {
str = str + " "+ ckAr[i].value
}
alert(str);
</script>
</body>
</html>
24
SELECT BOX

 Select Box
<select id="country">
<option selected="selected">Viet Nam</option>
<option value="Anh">Anh</option>
<option value="My">My</option>
</select>>

 On Firefox, access the selected value of the


Select Box using the value attribute

document.getElementById("country").value

 On Firefox, it is also possible to set the selected


value for the Select box using JavaScript
document.getElementById("country").value = "Mỹ"
25
DEMO SELECT BOX

<html ><head>
<script type="text/javascript">
function chonQuocGiaClick(){
var name = document.getElementById("country").value;
alert(name);
}
</script>
</head>
<body>
<select id="country">
<option selected="selected">Viet Nam</option>
<option value="Anh">Anh</option>
<option value="My">My</option>
</select>
<input type ="button" value="Chọn Quốc Gia"
onclick="chonQuocGiaClick()" />
</body></html>
26
DEMO SETTING VALUE FOR SELECT
BOX

<body>
<p><input type="button" value="Chau A" onclick= "chauAClick();" />
<input type="button" value="Chau Au" onclick="chauAuClick();"/>
<input type="button" value="Chau My" onclick="chauMy();" /> </p>
<p><select id="country">
<option selected="selected">Viet Nam</option>
<option value="Anh">Anh</option>
<option value="My">My</option>
</select></p>
</body>

Click vào
Chau Au

Click vào
Chau My
27
DEMO SETTING VALUE FOR SELECT
BOX
<script type="text/javascript">
function chauAClick() {
document.getElementById("country").value = "Viet Nam";
}
function chauAuClick() {
document.getElementById("country").value = "Anh";
}
function chauMy() {
document.getElementById("country").value = "My";
}
</script>
<body>
<p><input type="button" value="Chau A" onclick= "chauAClick();" />
<input type="button" value="Chau Au" onclick="chauAuClick();"/>
<input type="button" value="Chau My" onclick="chauMy();" /> </p>
<p><select id="country">
<option selected="selected">Viet Nam</option>
<option value="Anh">Anh</option>
<option value="My">My</option>
</select></p> 28
CHECKBOX

 Used for user selection


 CheckBox has two states: selected and
unselected

<input type="checkbox" value ="Kem que"


name="ckKem" checked="checked" />

 In JavaScript, use the CheckBox's checked


property to define and set the checkbox's state
 Value checked = true: CheckBox is selected
 Value checked = false: CheckBox is not checked

29
DEMO CHECKBOX
<html >
<body>
Cac loai kem trong cua hang:<br />
<input type="checkbox" value="Kem que" name="ckKem"/>Kem que <br />
<input type="checkbox" value="Kem dau" name="ckKem"/>Kem dau <br />
<input type="checkbox" value="Kem bo" name="ckKem"/>Kem bo <br />
<input type="checkbox" value="Kem vani" name="ckKem"/>Kem vani <br />
<input type="button" onclick="chonKem();" value="Chon kem" />
<p id="pKemDaChon"></p>
</body></html>

Ứng dụng liệt kê


những loại kem
được chọn

30
DEMO CHECKBOX
<html ><head>
<script type="text/javascript">
function chonKem() {
var str = "Nhung loai kem ban da chon la:<br/>";
var kemAr = document.getElementsByName("ckKem");
for (var i = 0; i < kemAr.length; i++) {
if (kemAr[i].checked) {
str= str + kemAr[i].value +"<br/>"
}
}
document.getElementById("pKemDaChon").innerHTML = str;
}
</script>
</head><body>
Cac loai kem trong cua hang:<br />
<input type="checkbox" value="Kem que" name="ckKem"/>Kem que <br />
<input type="checkbox" value="Kem dau" name="ckKem"/>Kem dau <br />
<input type="checkbox" value="Kem bo" name="ckKem"/>Kem bo <br />
<input type="checkbox" value="Kem vani" name="ckKem"/>Kem vani <br />
<input type="button" onclick="chonKem();" value="Chon kem" />
<p id="pKemDaChon"></p></body></html>
31
RADIO BUTTON

 Used for user selection


 CheckBox has two states: selected and
unselected
 Usually used in groups, in the group only one
Radio is selected

<input type="radio" value="Lon" name="rdSize" checked/>Lon<br />


<input type="radio" value="Vua" name="rdSize" />Vua<br />
<input type="radio" value="Nho" name="rdSize" />Nho<br />

 Radios with the same name belong to the same


group
32
DEMO RADIO BUTTON

Hiển thị loại kem


được chọn

33
DEMO RADIO BUTTON
var size="";
var sizeAr = document.getElementsByName("rdSize");
for (var i = 0; i < sizeAr.length; i++) {
if (sizeAr[i].checked) {
size = sizeAr[i].value;
}
}
str = str + "Kich thuoc ban da chon la: " + size;
document.getElementById("pKichThuocDaChon").innerHTML = size;

Hay chon kich thuoc kem:<br />


<input type="radio" value="Lon" name="rdSize" checked/>Lon<br />
<input type="radio" value="Vua" name="rdSize" />Vua<br />
<input type="radio" value="Nho" name="rdSize" />Nho<br />
Kich thuoc ban da chon la:
<p id="pKichThuocDaChon"></p>

34
How to use regular expressions
How to create and use regular expression
• A regular expression defines a pattern that can be
searched for in a string. This pattern is stored in a
regular expression object.
• To create a regular expression object, you can use
the RegExp constructor function or use regular
expression literal.
How to create and use regular expression
(cont.)
How to create and use regular expression
(cont.)
How to create regular expression patterns
How to create regular expression patterns
(cont.)
How to create regular expression patterns
(cont.)
How to create regular expression patterns
(cont.)
How to create regular expression patterns
(cont.)
Regular expressions for data validation
Regular expressions for data validation
(cont.)
How to handle exceptions
Concept of Exception
• An exception is an abnormal condition that arise
out of an extraordinary situation disrupting the
flow of program instruction.
• In programs, exceptions can
occur due to any of the following
reasons:
– Programming errors
– Client code errors
– Errors beyond the control of a
program
Handle checked exception

• Two ways handle checked exception:


– Throw the exception to the calling method
– Catch the exception and handle it
Why you need to handle an exception?

• If you don’t handle an exception:


– Program maybe crash
– User may be lost their data
– Some resource can’t reuse
How to create and throw Error objects
How to create and throw Error objects (cont.)
How to use try catch statement to handle
exceptions
• The syntax of the try statement
try {statements}
catch(errorName) {statements}
[finally {statements}]
How to use try catch statement to handle
exceptions (cont.)
How to use try catch statement to handle
exceptions (cont.)
The Register application
The Register application
The Register application
• The HTML Code
The Register application
The Register application
The Register application
The Register application
The Register application
The Register application
Summary
• A regular expression defines a pattern that can be searched for
in a string. This pattern is stored in a regular expression object.
• To create a regular expression object, you can use the RegExp
constructor function or use regular expression literal.
• An exception is an abnormal condition that arise out of
an extraordinary situation disrupting the flow of program
instruction.

You might also like