36
JavaScript III ECT 270 Robin Burke

JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Embed Size (px)

Citation preview

Page 1: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

JavaScript III

ECT 270

Robin Burke

Page 2: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Outline

Form validationRegular expressions

DOMJS document model reviewW3C DOM

Cross-browser scripting Style

Page 3: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Regular expressions

Form validation so farlegal valuesnot emptyequality

What if I want something more?valid email addressintegerssn

Page 4: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

What we need

A way to specify a patternmatch the pattern against the input

Solutionregular expressionsa syntax for expressing textual

patterns

Page 5: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Pattern components

Characters ordinary characters = themselves

Special characters \ | () [ { ^ $ * + ? . to use "escape" with backslash

Example \$

• matches any string containing a dollar sign @

• matches any string contains an "at" sign

Page 6: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Pattern components, cont'd

Character classes \d = any digit \w = any word character, alphanumeric \s = any whitespace character . = any character

Example \w\w\w\d

• matches foo5 but not fo5

Page 7: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Pattern components cont'd

Alternatives[ ] = any of the characters inside

• ranges OK| = any of the expressions joined

Examples[A-Z] matches any uppercase letter[A-Z]|[0-9] matches any uppercase

letter or a digit• same as [A-Z]|\d

Page 8: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Pattern components cont'd

Repetition ? = 0 or 1 occurrences * = 0..n occurrences + = 1..n occurrences {i} = i occurrences {i,j} = between i and j occurrences

Examples (0\.)?\d* matches 0.45 and 45 \d{3}-\d{2}-\d{4} matches 333-33-2222

• SSN pattern \d{3}-?\d{2}-?\d{4} matches even if dashes left out

Page 9: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Javascript implementation

Regular expression is created with / / delimiters re = /\d*/

Match function str.match (/exp/) value.match (/\d*/) usually in an if statement

Can also create a RegExp object re = new RegExp ("\d*") value.match (re)

Actually this doesn't work \ must be protected from JS string handling re = new RegExp ("\\d*")

Page 10: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Example

General pattern tester Validate a form containing a cash

quantity

Page 11: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Problem

(0\.)?\d+ matches 45 045 0.45 .....45 qq55mmm 1q1q1q1q

We might want to ensure the position of the match

Page 12: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

More pattern components

Positioning ^ = beginning

• must be the first thing in the pattern $ = end

• must be the end of the pattern Examples

^#.* matches a line whose first character is # ^(0\.)?\d+ matches 0.45 and 45, but not b45 ^(0\.)?\d+$ matches 0.45 and 45, but not b45

or 45b

Page 13: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Validating email

Many possible patterns ^[\\w-_\.]+\@([\\w]\.)+[\\w]+[\\w]$ ^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$ ^[a-zA-Z][\w\.-]*\w@\w[\w\.-]*[\w]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$ /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]

{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

Page 14: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

There's more...

Extraction of matched substrings Matching against previous matches in

a string Substitutions etc.

Page 15: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Summary

Regular expressions allow for complex patterns to be written

succinctly allow form validation to depend on data

format Regular expressions

can be dense and difficult to read can be difficult to debug require thorough documentation

Page 16: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

JS Document Model

Name-based Collection-based Some parts of the document not so

easy to accessespecially textual document content

Not possible to build an HTML document within JS

Page 17: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Example

Modifying document contentadd menu item

Page 18: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

W3C DOM

Document Object Model Based on the DOM for XML

not (very) HTML-specific Much more flexible

can build documents can access any part of the document

Levels 1 – Basic standard 2 – CSS / events

Page 19: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

HTML

<html><head><title>DOM Example</title></head><body><h1>DOM Example</h1><div name="pict" style="text-align: center; border-

width: 3 px; border-style: double"><img name="stickers" src="../w7/img/stickerface.gif"

width="230" height="238"> </div><p>Some text and <a href="lec1110.html">a link to the

lecture</a>. End of page.</p></body></html>

Page 20: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Internal representation

HTML

HEAD

TITLE

(text)

BODY

H1

(text)

DIV

IM

A

P

(text) (text)

(text)

Page 21: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Access via JS Document document links [0]

images [0]all

[0]

[1]

[2]

[3]

[4]

[5]

[6]

[7]

[8]

pict

stickers

HTML

HEAD

TITLE

(text)

BODY

H1

(text)

DIV

IM

A

P

(text) (text)

(text)

Page 22: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Example

Change the displayed imageuse images collectionuse name

Adding a new image

Page 23: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Problem

This is a mess new collections added for every purpose some collections browser-specific

W3C solution methods for traversal of the tree no special collections ability to generate collections

• based on tag name• based on id

Page 24: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

W3C DOM

Basic pieces Node

• general type NodeList

• wherever a collection is needed Element

• HTML element• subtype of Node

Text• a subtype of Node• contains only unmarked-up character data

Page 25: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Accessing DOM contents

document methods getElementsByTagName

• collected by tag (img, a, div, etc.) getElementById

• must be labeled by id, not name node methods

parentNode childNodes firstChild lastChild

element methods getAttribute setAttribute

Page 26: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Example

Changing the displayed imagedocument.getElementsByTagNamedocument.getElementById

Adding a new image

Page 27: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Modifying document content

factory methods of documentcreateElement (tagName)createTextNode

node modifiersappendChild (node)removeChild (node)insertBefore (newNode, currentNode)replaceChild (newNode, oldNode)

Page 28: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Summary

Pluses Available in both NS and IE

• not true of JS document

Conceptually simpler More capable

Minuses Code is wordier Implementation differences in browsers Some browser features still not standardized

Page 29: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Cross-browser headaches

The more advanced features you usethe more likely it is that you'll run into

cross-browser issues biggest problem

handling of the DIV tagnetscape 4.0 added a new concept

"layers"• now wisely abandoned

Page 30: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Standard solution

conditional codingdetermine browser type

• remember window.navigator?

execute appropriate code problem

breaks with new browser versions

Page 31: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Browser-detection example

isNS = false;isIE = false;if (window.navigator.appName.match(/IE/)) isIE=true;

elseif (window.navigator.appName.match(/Netscape|Mozilla/))

isNS = true;if (isNS){ object.moveTo(x, y);} else if (isIE) { object.pixelLeft=x; object.pixelTop=y;}

Page 32: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Better method

Test for specific features that you need

If your code depends on the .all collectiontest for its presence

Problemlots of if statements

Page 33: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Feature-detection example

isNS = false;isIE = false;if (document.all){

isIE=true;) else if (document.layers){

isNS=true;}if (isNS){ object.moveTo(x, y);} else if (isIE) { object.pixelLeft=x; object.pixelTop=y;}

Page 34: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Best solution

Cross-browser API package "application programming interface" a collection of JS functions provide a browser-neutral interface

Example DOMjs.js from book

• a uniform API for style manipulation comprehensive commercial versions exist

Include by using a stand-alone script tag <script language="Javascript"

src="DOMapi.js">

Page 35: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Using an API

Benefitcan forget about browser details

Problemmust learn new API

Good newsnewer Mozilla versions have

eliminated many of the differencesSeparate API less necessary

Page 36: JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

Next week

Styleespecially positioningspecial effects