Week 3 User Input Validation with Java Script

  • Slides: 52
Download presentation
Week 3 – User Input Validation with Java. Script Client-side user input validation n

Week 3 – User Input Validation with Java. Script Client-side user input validation n Selected features of the Java. Script language n Use of Java. Script form user input validation n Regular Expressions Event Handlers 1

User Input Validation Java, Perl, etc. Server Browser POST or GET Form Validation Request

User Input Validation Java, Perl, etc. Server Browser POST or GET Form Validation Request Validation Result Active Server-side Code Response Page Validation Java. Script Validation Code Update Database Client-side Validation Server-side Validation COMP/DCOM 461 – CWB 2

Client-side User Input Validation n Avoids round-trip request to server when form has obvious

Client-side User Input Validation n Avoids round-trip request to server when form has obvious errors n n Delays (when network or server is slow) Disruption of page transition Unnecessary server traffic Notifying user of error – alternatives: n n Pop-up “alert box” (annoying, disruptive) Disable submit button plus on-form message (less obvious) COMP/DCOM 461 – CWB 3

Server-side User Input Validation n Client-side validation does not eliminate the need to validate

Server-side User Input Validation n Client-side validation does not eliminate the need to validate user input on the server n n A malicious user could copy and modify your page to eliminate the client-side validation Server-side re-validation is crucial if bad user data could be harmful or insecure Client-side validation is to be considered only a convenience for the user and a means to reduce unnecessary traffic on the server Sometimes validation is too hard to do on the client COMP/DCOM 461 – CWB 4

Java. Script n n Scripting language designed for use in client-side programming in web

Java. Script n n Scripting language designed for use in client-side programming in web pages In fact, a powerful, full-featured, objectoriented language Originally created by Netscape, which initially called it Live. Script Standardized by the European Computer Manufacturers Association: http: //www. ecma-international. org/publications/standards/Ecma-262. htm COMP/DCOM 461 – CWB 5

Primary Differences from Java n No strong typing n n n The type of

Primary Differences from Java n No strong typing n n n The type of variables are not declared A variable’s type can be changed dynamically Objects work more like a hash table than a structure n Creating class instances (objects) uses a “prototype” mechanism n n n An object is created by making a copy of a prototype object associated with the class Inheritance: use This means that you can change the class dynamically a prototype for by changing the prototype object the prototype The members of an object are called properties. Properties can be added, deleted, or changed in type Property names can be arbitrary strings COMP/DCOM 461 – CWB Continued … 6

Primary Differences from Java, cont. n Functions are objects n n A constructor function

Primary Differences from Java, cont. n Functions are objects n n A constructor function plays the role of the class object – what would be static fields in Java are properties of the constructor function. There are built-in objects referring to the browser window and its various sub-objects COMP/DCOM 461 – CWB 7

Objects in a Page As appearing on the screen As appearing in the Java.

Objects in a Page As appearing on the screen As appearing in the Java. Script Document Object Model window Window HTML document A form document A text field A checkbox form text COMP/DCOM 461 – CWB checkbox 8

The Browser Invoking Java. Script Code User Performs Some Action Such as clicking, typing,

The Browser Invoking Java. Script Code User Performs Some Action Such as clicking, typing, etc. Find Object Corresponding To User Operation Event Handler Defined? Normal Behavior for the User Action Yes Execute Java. Script for the Event Handler true Done COMP/DCOM 461 – CWB Return Value false 9

Setting an Event Handler <form id="my. Form" method="get" action="…" onsubmit="return check(this)" > n n

Setting an Event Handler <form id="my. Form" method="get" action="…" onsubmit="return check(this)" > n n Declares that the code return check(this) will be executed when the form is about to be submitted The code check(this)is a call to a function called check. n n The argument this refers to the Java. Script object associated with the event (which is the form in this case) The submit will actually occur only if the check function returns true. COMP/DCOM 461 – CWB 10

How Do We Define the Function check? <script language="Java. Script"> <!-function check(form) { if(form.

How Do We Define the Function check? <script language="Java. Script"> <!-function check(form) { if(form. t 1. value == "") { alert("The text field is empty. "); return false; } if(! form. c 1. checked) { alert("The checkbox is not checked. "); return false; } return true; } //--> </script> n Put this code in the <head> n n The <script> tag “hides” the text inside it from HTML parsing n n It will also work in the <body>, but in the <head> is preferred. So <, etc. can be used without problem The comment lines are used to prevent problems in older browsers that don’t recognize the <script> tag Alternatively, the Java. Script code can be read in from a file – discussed later. What does this code mean? COMP/DCOM 461 – CWB 11

Defining a Function <script language="Java. Script"> <!-function check(form) { var txt. Fld = form.

Defining a Function <script language="Java. Script"> <!-function check(form) { var txt. Fld = form. t 1; if(txt. Fld. value == "") { alert("The text field is empty. "); return false; } Defines a function and one parameter • Recall: The parameter is a reference to the form object • No type is declared for the argument • No return value type is declared Declares a local variable called “txt. Fld” and initializes it • No type is declared for the variable if(! form. c 1. checked) • The var is optional, but serves to make { alert("The checkbox is not checked. "); the variable local, thus preventing return false; collisions with variables called “txt. Fld” } The txt. Fld var is included that might be used elsewhere return true; here only to illustrate the } • form contains properties that var concept. It’s //--> unnecessary and doesn’t references all the elements of the form </script> appear on subsequent by ID or name slides. COMP/DCOM 461 – CWB 12

Defining a Function <script language="Java. Script"> <!-function check(form) { form. t 1. value refers

Defining a Function <script language="Java. Script"> <!-function check(form) { form. t 1. value refers to the value of the text field named t 1. if(form. t 1. value == "") { alert("The text field is empty. "); return false; } • This tests whether the text field’s value is the empty string. if(! form. c 1. checked) { alert("The checkbox is not checked. "); return false; } return true; } //--> </script> • Note that string comparison is done with the == operator (unlike Java) • The attributes of a tag will appear as properties of the object associated with the object. COMP/DCOM 461 – CWB 13

Defining a Function The alert function is built in <script language="Java. Script"> <!-function check(form)

Defining a Function The alert function is built in <script language="Java. Script"> <!-function check(form) { • The alert function pops up a confirmer box with the given text and an OK button. • This is an example to illustrate the coding technique. In good design practice, a more detailed, user-friendly message might be given. if(form. t 1. value == "") { alert("The text field is empty. "); return false; } if(! form. c 1. checked) { alert("The checkbox is not checked. "); return false; } return true; } //--> </script> The check function returns false. • This tells the browser to not continue with the submit. COMP/DCOM 461 – CWB 14

Defining a Function This tests if the checkbox is checked or not. <script language="Java.

Defining a Function This tests if the checkbox is checked or not. <script language="Java. Script"> <!-function check(form) { • The checked attribute is a Boolean. • The ! is the NOT operator. if(form. t 1. value == "") { alert("The text field is empty. "); return false; } • It is, of course, pointless to have a single checkbox that you require to be checked (why bother? ). • This is only an example. if( ! form. c 1. checked ) { alert("The checkbox is not checked. "); return false; } return true; } //--> </script> • Normally, there would be multiple checkboxes and you would verify that at least one of them is checked – or whatever you wish. COMP/DCOM 461 – CWB 15

Defining a Function <script language="Java. Script"> <!-function check(form) { if(form. t 1. value ==

Defining a Function <script language="Java. Script"> <!-function check(form) { if(form. t 1. value == "") { alert("The text field is empty. "); return false; } Again there is a popup alert box and the function returns false to indicate that the submit should not occur. if( ! form. c 1. checked ) { alert("The checkbox is not checked. "); return false; } return true; } //--> </script> The check function returns true if everything is OK. This causes the submit to actually occur. COMP/DCOM 461 – CWB 16

HTML for a Submit Example <html> <head> <title>Submit Example</title> <script language="Java. Script"> Java. Script

HTML for a Submit Example <html> <head> <title>Submit Example</title> <script language="Java. Script"> Java. Script from previous slides goes here. </script> </head> <body> <form id="my. Form" method="get" action="javascript: alert('submitted')" onsubmit="return check(this); " > <input type="text" name="t 1" > <input type="checkbox" name="c 1" value="c 1" > <input type="submit" > </form> </body> </html> COMP/DCOM 461 – CWB Temporary action URL for testing 17

The javascript URL Notice the use of single Scheme quotes inside double quotes action="javascript:

The javascript URL Notice the use of single Scheme quotes inside double quotes action="javascript: alert('submitted')" n n The URL uses javascript instead of http for the scheme. This is understood by the browser to mean n n Don’t send a get request to the server Instead, execute the given text as Java. Script code The resulting value is used as the HTML for a new page To stay on the same page, suppress the value with: void(<expression>) This technique can be very useful for debugging and testing – and sometimes useful for production as well. COMP/DCOM 461 – CWB 18

Sidebar: Bookmarklets n n Think about the possibilities of having bookmarks or links on

Sidebar: Bookmarklets n n Think about the possibilities of having bookmarks or links on your browser that use the javascript: form of URL Hint: remember to use the void syntax to suppress creating a new page void (some Java. Script expression) COMP/DCOM 461 – CWB 19

What Have We Done So Far? n Added an onsubmit attribute to the <form>

What Have We Done So Far? n Added an onsubmit attribute to the <form> tag that calls the check function, passing a reference to the form by using the this keyword. Defined the check function in a <script> tag n It tests the values of form fields n On error, it pops up an alert box and returns false n If all is OK, it returns true Demo: http: //cs. franklin. edu/~brownc/461/submit. Example. html n n Comment on demo: It would be better to list all errors at once in the alert box! COMP/DCOM 461 – CWB 20

Alternative for Including Java. Script Code <script language="Java. Script" src='data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20viewBox=%220%200%20415%20289%22%3E%3C/svg%3E' data-src="submit. Example. js" > </script>

Alternative for Including Java. Script Code <script language="Java. Script" src="submit. Example. js" > </script> Still need the end tag n n Demo: http: //cs. franklin. edu/~brownc/461/submit. Example. With. SRC. html Benefits n n Can share Java. Script source among many pages Removes a lot of clutter from the page – improves readability n n n Becomes really important with servlet- and JSP-generated pages! Helps to separate page design and functionality Hides your Java. Script code from the casual observer n n But, of course, one can always access the. js file separately. There are techniques for encrypting the Java. Script file, but we won’t go into them. COMP/DCOM 461 – CWB 21

Getting the values of form fields Type of <input> Attribute checkbox or radio checked

Getting the values of form fields Type of <input> Attribute checkbox or radio checked Attribute Values true or false value the value to be submitted if true file value the URL of the file to be uploaded hidden value the value to be submitted text or password value the text to be submitted button, submit, reset <select> N/A selected. Index options[index]. value <textarea> value 0 -based number of the <option> that is selected the value to be submitted the text to be COMP/DCOM 461 – CWB submitted 22

Special Code for Accessing Radio Buttons n n Java-style for statement Recall, the radio

Special Code for Accessing Radio Buttons n n Java-style for statement Recall, the radio buttons that work as a group are given the same name Thus, Java. Script uses an array to represent them: An array of all the elements var radio. Group = form. user. Rating; with the name user. Rating var rb; var value. Checked = ""; for(rb = 0; rb < radio. Group. length; rb++) Arrays have a built if(radio. Group[rb]. checked) -in length value. Checked = radio. Group[rb]. value; alert("The value checked is: " + value. Checked); property. if(value. Checked == "bad") #unfair validation! return false; return true; } Demo: http: //cs. franklin. edu/~brownc/461/submit. Example. With. Radio. html COMP/DCOM 461 – CWB 23

Exercise n n Given a page with 3 radio buttons, add a validation function

Exercise n n Given a page with 3 radio buttons, add a validation function to ensure that one is selected. (We’ll work together as a class. ) Starting point: http: //cs. franklin. edu/~brownc/461/In. Class. Validation. Radio. html COMP/DCOM 461 – CWB 24

Validation Upon Field Change n n n Check validation as soon as user changes

Validation Upon Field Change n n n Check validation as soon as user changes a field Benefit: more convenient for user to know of error right away Problems: n n Can’t check for required fields Won’t prevent submit, so you have to re-validate with onsubmit Can give a spurious error when one of two dependent fields are changed Can be annoying if done clumsily COMP/DCOM 461 – CWB 25

Validation Upon Field Change, cont. onchange event occurs n n field is losing focus

Validation Upon Field Change, cont. onchange event occurs n n field is losing focus but only if its value has changed <input type=“checkbox” name=“opt 1” onchange=“validate(this)” > <textarea cols=“ 30” rows=“ 10” name=“comment” onchange=“validate(this)” > COMP/DCOM 461 – CWB 26

The onchange Event n Event occurs on a form field. n n The this

The onchange Event n Event occurs on a form field. n n The this variable refers to the field, not the form You have the choice of n n Defining a separate validation function for each field or Using a common validation function that applies different rules for different fields: if(field. name == “password”) … n n Event fires when the form element loses focus but only if its value has changed Gives you the ability to tell users of errors immediately COMP/DCOM 461 – CWB 27

Example: Verify a 5 Digit Note: Use the Zip Code keyboard double <input type=“text”

Example: Verify a 5 Digit Note: Use the Zip Code keyboard double <input type=“text” name=“zipcode” on. Change=“validate 5 Zip(this)” > quote character. These open and close quotes are an artifact of Power. Point function validate 5 Zip(field) { //verify it’s a 5 -digit zip code var zip = field. value; if(zip. length != 5 || is. Na. N(parse. Int(zip)) { alert(“please enter a 5 digit zip code. ”); return false; Converts string } to integer and checks if result is return true; “not a number” } COMP/DCOM 461 – CWB 28

Example Recast as a Single Validation Function n The validate function: function validate(field) {

Example Recast as a Single Validation Function n The validate function: function validate(field) { Note the switch statement works with strings! <input type=“text” name=“zipcode” onchange=“validate(this)” > var val = field. value; switch(field. name) { case "zipcode": if(val. length != 5 || is. Na. N(parse. Int(val)) { alert(“please enter a 5 digit zip code. ”); return false; } break; case … //Other fields tested here } return true; } COMP/DCOM 461 – CWB 29

A Few More Java. Script Details Emphasizing Differences from Java 30

A Few More Java. Script Details Emphasizing Differences from Java 30

Accessing Object Properties n n Properties are somewhat like class members in Java Reference

Accessing Object Properties n n Properties are somewhat like class members in Java Reference properties in 2 ways: 1. 2. n var txtfld = obj. user. Name; var txtfld = obj["user. Name"]; Properties can be added dynamically: obj. my. Own. Property = 92; Only valid when property name is alphanumeric, starting with letter. Any format of property name; Think: array with non-numerical indices Creates my. Own. Property if it’s not already present COMP/DCOM 461 – CWB 31

Strings n Strings can be concatenated with the + operator: var s = "My

Strings n Strings can be concatenated with the + operator: var s = "My name is " + the. Name; n Most values can be converted automatically to strings: var n = 7; var s = "The number is " + n; n Strings have a property called length n Not a length() method as in Java COMP/DCOM 461 – CWB 32

String Functions Strings have many built-in functions. Here a few examples: n n Returns

String Functions Strings have many built-in functions. Here a few examples: n n Returns a string, not a character char. At(n) – get the nth character (0 based) var i = name. char. At(3); //get 4 th character in name index. Of(substring, n) – search for the substring in the string and return its index (0 -based character number) n n is optional and indicates where to start looking n n n returns -1 if the substring is not found substring(s, t) – extract characters from the string, starting at index s up to but not including index t match, search, replace – discussed later COMP/DCOM 461 – CWB 33

Arrays n Arrays are objects that have properties whose names are integer numbers n

Arrays n Arrays are objects that have properties whose names are integer numbers n n Must use the [ ] notation, not the. notation Special length property gives the number of elements (mostly) The name of the var s = ""; radio group var radios = form. choices; for(var r = 0; r < radios. length; r++) s = s + " " + radios[r]. value; var first. Radio = radios[0]; COMP/DCOM 461 – CWB 34

Quotes in Java. Script and HTML n n Single quotes and double quotes are

Quotes in Java. Script and HTML n n Single quotes and double quotes are equivalent. Inside a double-quoted string, use single quotes to enter a nested quote: onchange="alert('It changed!')" var message = "It's OK. ". n Inside a single-quoted string, use double quotes to enter a nested quote: var message = 'Please see "Instructions"'; n Quotes can also be escaped with var message = "Please see "Instructions""; n Not recognized by HTML attributes COMP/DCOM 461 – CWB 35

If Statements n n In Java, the expression inside the if(…) must be of

If Statements n n In Java, the expression inside the if(…) must be of type boolean In Java. Script, any type of expression is converted to a Boolean value if possible n n n n Number: converted to true when non-zero String: converted to true when non-empty (so “ 0” is true; “false” is true; “” is false) Object: always converts to true Array: inconsistent across browsers Function: true null: false undefined: false COMP/DCOM 461 – CWB 36

Looping Statements n n n while statement: like Java for statement: like Java, except

Looping Statements n n n while statement: like Java for statement: like Java, except … for(x in a) n n Automatically iterates through an array or through the properties of an object In each iteration, x is set to the array index or the name of the property for(x in form. elements) alert("Element " + x + "'s value is " + form. elements[x]. value ); elements is a property COMP/DCOM 461 – CWB of the form element that is a collection of all the form’s elements 37

Functions n Named functions function my. Function(a, b) { … } n Accessed as

Functions n Named functions function my. Function(a, b) { … } n Accessed as var value = my. Function(4, "Hello”); n Anonymous functions my. Object. a. Function = function(a, b) {…} n Creates a function that is a method of var other. Value = my. Object. a. Function(9, the object 0); Accessed as COMP/DCOM 461 – CWB 38

Regular Expression Matching Fancier Validation 39

Regular Expression Matching Fancier Validation 39

Regular Expression Patterns in Java. Script n n n /hello/ matches “hello” /[jbs]unk/ matches

Regular Expression Patterns in Java. Script n n n /hello/ matches “hello” /[jbs]unk/ matches “junk”, “bunk”, or “sunk” /d/ -- matches a digit /ab*c/ matches an “a” and a “c” with zero or more “b”s between them /ab+c/ matches an “a” and a “c” with one or more “b”s between them /a. c/ matches an “a” and a “c” with exactly 1 arbitrary character between them /(asdfg){3}/ matches 3 repetitions of the string “asdfg” /bite? / matches bit or bite /^bat/ matches “bat” at the beginning of the string /ment$/ matches “ment” at the end of the string /large|medium|small/ matches any of the 3 words COMP/DCOM 461 – CWB 40

Selected Summary of the Pattern Syntax n n n An item is a single

Selected Summary of the Pattern Syntax n n n An item is a single character or a group enclosed in parentheses ? the previous item (character or group) is optional * the previous items is optional and may appear any number of times + the previous items is not optional but may appear any number of times {n} the previous item is required to appear n times ^ matches the beginning of the string $ matches the end of the string d matches any digit w matches a “word” s matches any whitespace character […] matches any of the characters between the [] | alternation; a|b matches a or b See pages 342, 343 in Anderson-Freed. COMP/DCOM 461 – CWB 41

A Zip Code Pattern n To match 5 or 9 digit zip codes: /^d{5}(-d{4})?

A Zip Code Pattern n To match 5 or 9 digit zip codes: /^d{5}(-d{4})? $/ Match must start at the Matches beginning exactly 5 digits Matches a dash followed of the by 4 digits string Makes the dash and 4 digits optional COMP/DCOM 461 – CWB Match must end at the end of the string 42

Regular Expression Demo n http: //cs. franklin. edu/~brownc/461/regexpdemo. html COMP/DCOM 461 – CWB 43

Regular Expression Demo n http: //cs. franklin. edu/~brownc/461/regexpdemo. html COMP/DCOM 461 – CWB 43

Using Patterns in Java. Script Code The String method search(pattern) n n returns the

Using Patterns in Java. Script Code The String method search(pattern) n n returns the numerical index of the substring matching the pattern returns -1 if there is no match. if(zip. search( /^d{5}(-d{4})? $/ ) == -1) { alert(“Please enter a 5 or 9 digit zip code”); } COMP/DCOM 461 – CWB 44

Using Patterns in Java. Script Code, alt. The String method match(pattern) null evaluates to

Using Patterns in Java. Script Code, alt. The String method match(pattern) null evaluates to false n n returns an object describing the match returns null if there is no match if( !zip. match( /^d{5}(-d{4})? $/ ) ) { alert(“Please enter a 5 or 9 digit zip code”); } COMP/DCOM 461 – CWB 45

5 or 9 Digit Zip Code Field Validation Function function validate. Zip(field) { var

5 or 9 Digit Zip Code Field Validation Function function validate. Zip(field) { var zip = field. value; if( zip. search( /^d{5}(-d{4})? $/ ) == -1 ) { alert("Please enter a 5 or 9 digit zip code. "); return false; } return true; } COMP/DCOM 461 – CWB 46

Some regular expression references n http: //www. jansfreeware. com/articles/regexpress. html n http: //www. visibone.

Some regular expression references n http: //www. jansfreeware. com/articles/regexpress. html n http: //www. visibone. com/regular-expressions/ COMP/DCOM 461 – CWB 47

Additional Topics 48

Additional Topics 48

onsubmit Validation Combined with onchange Validation Re-validate fields with onchange validation in case they

onsubmit Validation Combined with onchange Validation Re-validate fields with onchange validation in case they remain unchanged from a default value: function check(form) { if(!validate. Zip(form. zip 59) ) return false; • Invoke the onchange validation function used in the onsubmit handler if(!form. c 1. checked) • Avoid duplicated code. { Sidebar alert("The checkbox is …"); Be careful of alerts and other return false; messages when you invoke a } validation function from inside return true; } another. Check for required fields Avoid duplicate warnings and other annoying behavior. COMP/DCOM 461 – CWB 49

Cross-Field Validation When one field’s validation depends on the value of another field: n

Cross-Field Validation When one field’s validation depends on the value of another field: n In onsubmit validation, there’s no new problem since the form object is passed as a parameter n In onchange validation, you access the form object through the field’s form property: function validate. Ship. Address(field) { var is. Same. Address = field. form. same. Address. Check. checked; if(!is. Same. Address) //if user hasn’t said ship address is same if(!field. value) { alert("Please enter a shipping address or check the box" + ""Shipping Address Is Same As Billing Address""); return false; } return true; } COMP/DCOM 461 – CWB 50

Next Week’s Assignment http: //cs. franklin. edu/Syllabus/comp 461/assignments. html#validation In Registration Page n n

Next Week’s Assignment http: //cs. franklin. edu/Syllabus/comp 461/assignments. html#validation In Registration Page n n User ID must be at least 4 characters. How do we do this? Validation of state, postal code, and telephone fields depend on the country. Note: the telephone field is never required In Checkout Page n n Normally validation of all fields would occur. I do not require you to repeat the work done on the Registration Page. COMP/DCOM 461 – CWB 51

Next Topic n n n Server-side page generation using Perl Next week we introduce

Next Topic n n n Server-side page generation using Perl Next week we introduce the Perl language In two weeks, we cover selected details of handling forms and other actions COMP/DCOM 461 – CWB 52