JavaScript III ECT 270 Robin Burke
Outline Validation examples password more complex Form validation Regular expressions
Examples
Regular expressions Form validation so far legal values not empty equality What if I want something more? valid 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 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 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 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 Many possible patterns 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