360 likes | 510 Views
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 far legal values not empty equality What if I want something more? valid email address
E N D
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 far • legal values • not empty • equality • What if I want something more? • valid email address • integer • ssn
What we need • A way to specify a pattern • match the pattern against the input • Solution • regular expressions • a syntax for expressing textual patterns
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
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
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
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
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*")
Example • General pattern tester • Validate a form containing a cash quantity
Problem • (0\.)?\d+ matches • 45 • 045 • 0.45 • .....45 • qq55mmm • 1q1q1q1q • We might want to ensure the position of the match
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
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,}))$/
There's more... • Extraction of matched substrings • Matching against previous matches in a string • Substitutions • etc.
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
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
Example • Modifying document content • add menu item
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
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>
Example • Change the displayed image • use images collection • use name • Adding a new image
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
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
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
Example • Changing the displayed image • document.getElementsByTagName • document.getElementById • Adding a new image
Modifying document content • factory methods of document • createElement (tagName) • createTextNode • node modifiers • appendChild (node) • removeChild (node) • insertBefore (newNode, currentNode) • replaceChild (newNode, oldNode)
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
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
Standard solution • conditional coding • determine browser type • remember window.navigator? • execute appropriate code • problem • breaks with new browser versions
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; }
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
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; }
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">
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
Next week • Style • especially positioning • special effects