Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "JavaScript III ECT 270 Robin Burke. Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style."— Presentation transcript:

1 JavaScript III ECT 270 Robin Burke

2 Outline Form validation Regular expressions DOM JS document model review W3C DOM Cross-browser scripting Style

3 Regular expressions Form validation so far legal values not empty equality What if I want something more? valid email address integer ssn

4 What we need A way to specify a pattern match the pattern against the input Solution regular expressions a syntax for expressing textual patterns

5 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

6 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

7 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

8 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

9 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*")

10 Example General pattern tester Validate a form containing a cash quantity

11 Problem (0\.)?\d+ matches 45 045 0.45.....45 qq55mmm 1q1q1q1q We might want to ensure the position of the match

12 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

13 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,}))$/

14 There's more... Extraction of matched substrings Matching against previous matches in a string Substitutions etc.

15 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

16 JS Document Model Name-based Collection-based Some parts of the document not so easy to access especially textual document content Not possible to build an HTML document within JS

17 Example Modifying document content add menu item

18 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

19 HTML DOM Example DOM Example Some text and a link to the lecture. End of page.

20 Internal representation

21 Access via JS Document

22 Example Change the displayed image use images collection use name Adding a new image

23 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

24 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

25 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

26 Example Changing the displayed image document.getElementsByTagName document.getElementById Adding a new image

27 Modifying document content factory methods of document createElement (tagName) createTextNode node modifiers appendChild (node) removeChild (node) insertBefore (newNode, currentNode) replaceChild (newNode, oldNode)

28 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

29 Cross-browser headaches The more advanced features you use the more likely it is that you'll run into cross-browser issues biggest problem handling of the DIV tag netscape 4.0 added a new concept "layers" now wisely abandoned

30 Standard solution conditional coding determine browser type remember window.navigator? execute appropriate code problem breaks with new browser versions

31 Browser-detection example isNS = false; isIE = false; if (window.navigator.appName.match(/IE/)) isIE=true; else if (window.navigator.appName.match(/Netscape|Mozilla/)) isNS = true; if (isNS) { object.moveTo(x, y); } else if (isIE) { object.pixelLeft=x; object.pixelTop=y; }

32 Better method Test for specific features that you need If your code depends on the.all collection test for its presence Problem lots of if statements

33 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; }

34 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

35 Using an API Benefit can forget about browser details Problem must learn new API Good news newer Mozilla versions have eliminated many of the differences Separate API less necessary

36 Next week Style especially positioning special effects


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

Similar presentations


Ads by Google