Week 3 - PowerPoint PPT Presentation

About This Presentation
Title:

Week 3

Description:

Week 3 User Input Validation with JavaScript Client-side user input validation Selected features of the JavaScript language Use of JavaScript for form user input ... – PowerPoint PPT presentation

Number of Views:77
Avg rating:3.0/5.0
Slides: 53
Provided by: Coli1162
Learn more at: https://cs.franklin.edu
Category:
Tags: coding | looping | week

less

Transcript and Presenter's Notes

Title: Week 3


1
Week 3 User Input Validation with JavaScript
  • Client-side user input validation
  • Selected features of the JavaScript language
  • Use of JavaScript for form user input validation
  • Regular Expressions
  • Event Handlers

2
User Input Validation
Java, Perl, etc.
Server
Browser
Active Server-side Code
POST or GET
Form
Response Page
ValidationResult
ValidationRequest
Validation
JavaScript Validation Code
Update
Database
Client-side Validation
Server-side Validation
3
Client-side User Input Validation
  • Avoids round-trip request to server when form has
    obvious errors
  • Delays (when network or server is slow)
  • Disruption of page transition
  • Unnecessary server traffic
  • Notifying user of error alternatives
  • Pop-up alert box (annoying, disruptive)
  • Disable submit button plus on-form message (less
    obvious)

4
Server-side User Input Validation
  • Client-side validation does not eliminate the
    need to validate user input on the server
  • 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

5
JavaScript
  • Scripting language designed for use in
    client-side programming in web pages
  • In fact, a powerful, full-featured,
    object-oriented language
  • Originally created by Netscape, which initially
    called it LiveScript
  • Standardized by the European Computer
    Manufacturers Association

http//www.ecma-international.org/publications/sta
ndards/Ecma-262.htm
6
Primary Differences from Java
  • No strong typing
  • The type of variables are not declared
  • A variables type can be changed dynamically
  • Objects work more like a hash table than a
    structure
  • Creating class instances (objects) uses a
    prototype mechanism
  • An object is created by making a copy of a
    prototype object associated with the class
  • This means that you can change the class
    dynamically by changing the prototype object
  • The members of an object are called properties.
  • Properties can be added, deleted, or changed in
    type
  • Property names can be arbitrary strings

Inheritance use a prototype for the prototype
Continued
7
Primary Differences from Java, cont.
  • Functions are objects
  • 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

8
Objects in a Page
As appearing on the screen
As appearing in the JavaScript Document Object
Model
window
Window
HTML document
A form
document
A text field
form
A checkbox
text
checkbox
9
The Browser Invoking JavaScript Code
User Performs Some Action
Such as clicking, typing, etc.
Find Object Corresponding To User Operation
Event Handler Defined?
Execute JavaScript for the Event Handler
Yes
Return Value
Normal Behavior for the User Action
true
false
Done
10
Setting an Event Handler
  • ltform id"myForm" method"get" action""
    onsubmit"return check(this)" gt
  • 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.
  • The argument this refers to the JavaScript object
    associated with the event (which is the form in
    this case)
  • The submit will actually occur only if the check
    function returns true.

11
How Do We Define the Function check?
  • ltscript language"JavaScript"gt
  • lt!--
  • function check(form)
  • if(form.t1.value "")
  • alert("The text field is empty.")
  • return false
  • if(! form.c1.checked)
  • alert("The checkbox is not checked.")
  • return false
  • return true
  • //--gt
  • Put this code in the ltheadgt
  • It will also work in the ltbodygt, but in the
    ltheadgt is preferred.
  • The ltscriptgt tag hides the text inside it from
    HTML parsing
  • So lt, etc. can be used without problem
  • The comment lines are used to prevent problems in
    older browsers that dont recognize the ltscriptgt
    tag
  • Alternatively, the JavaScript code can be read in
    from a file discussed later.
  • What does this code mean?

12
Defining a Function
  • 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
  • ltscript language"JavaScript"gt
  • lt!--
  • function check(form)
  • var txtFld form.t1
  • if(txtFld.value "")
  • alert("The text field is empty.")
  • return false
  • if(! form.c1.checked)
  • alert("The checkbox is not checked.")
  • return false
  • return true
  • //--gt
  • Declares a local variable called txtFld and
    initializes it
  • No type is declared for the variable
  • The var is optional, but serves to make the
    variable local, thus preventing collisions with
    variables called txtFld that might be used
    elsewhere
  • form contains properties that references all the
    elements of the form by ID or name

The txtFld var is included here only to
illustrate the var concept. Its unnecessary and
doesnt appear on subsequent slides.
13
Defining a Function
  • ltscript language"JavaScript"gt
  • lt!--
  • function check(form)
  • if(form.t1.value "")
  • alert("The text field is empty.")
  • return false
  • if(! form.c1.checked)
  • alert("The checkbox is not checked.")
  • return false
  • return true
  • //--gt
  • form.t1.value refers to the value of the text
    field named t1.
  • This tests whether the text fields value is the
    empty string.
  • The attributes of a tag will appear as
    properties of the object associated with the
    object.
  • Note that string comparison is done with the
    operator (unlike Java)

14
Defining a Function
  • The alert function is built in
  • 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.
  • ltscript language"JavaScript"gt
  • lt!--
  • function check(form)
  • if(form.t1.value "")
  • alert("The text field is empty.")
  • return false
  • if(! form.c1.checked)
  • alert("The checkbox is not checked.")
  • return false
  • return true
  • //--gt
  • The check function returns false.
  • This tells the browser to not continue with the
    submit.

15
Defining a Function
  • This tests if the checkbox is checked or not.
  • The checked attribute is a Boolean.
  • The ! is the NOT operator.
  • It is, of course, pointless to have a single
    checkbox that you require to be checked (why
    bother?).
  • This is only an example.
  • Normally, there would be multiple checkboxes and
    you would verify that at least one of them is
    checked or whatever you wish.
  • ltscript language"JavaScript"gt
  • lt!--
  • function check(form)
  • if(form.t1.value "")
  • alert("The text field is empty.")
  • return false
  • if( ! form.c1.checked )
  • alert("The checkbox is not checked.")
  • return false
  • return true
  • //--gt

16
Defining a Function
  • ltscript language"JavaScript"gt
  • lt!--
  • function check(form)
  • if(form.t1.value "")
  • alert("The text field is empty.")
  • return false
  • if( ! form.c1.checked )
  • alert("The checkbox is not checked.")
  • return false
  • return true
  • //--gt

Again there is a popup alert box and the function
returns false to indicate that the submit should
not occur.
The check function returns true if everything is
OK. This causes the submit to actually occur.
17
HTML for a Submit Example
  • lthtmlgt
  • ltheadgt
  • lttitlegtSubmit Examplelt/titlegt
  • ltscript language"JavaScript"gt
  • lt/scriptgt
  • lt/headgt
  • ltbodygt
  • ltform id"myForm" method"get"
    action"javascriptalert('submitted')"
  • onsubmit"return check(this)" gt
  • ltinput type"text" name"t1" gt
  • ltinput type"checkbox" name"c1" value"c1" gt
  • ltinput type"submit" gt
  • lt/formgt
  • lt/bodygt
  • lt/htmlgt

JavaScript from previous slides goes here.
Temporary action URL for testing
18
The javascript URL Scheme
Notice the use of single quotes inside double
quotes
  • action"javascriptalert('submitted')"
  • The URL uses javascript instead of http for the
    scheme.
  • This is understood by the browser to mean
  • Dont send a get request to the server
  • Instead, execute the given text as JavaScript
    code
  • The resulting value is used as the HTML for a new
    page
  • To stay on the same page, suppress the value
    with
  • void(ltexpressiongt)
  • This technique can be very useful for debugging
    and testing and sometimes useful for production
    as well.

19
Sidebar Bookmarklets
  • 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 JavaScript expression)

20
What Have We Done So Far?
  • Added an onsubmit attribute to the ltformgt tag
    that calls the check function, passing a
    reference to the form by using the this keyword.
  • Defined the check function in a ltscriptgt tag
  • It tests the values of form fields
  • On error, it pops up an alert box and returns
    false
  • If all is OK, it returns true
  • Demo http//cs.franklin.edu/brownc/461/submitExa
    mple.html

Comment on demo It would be better to list all
errors at once in the alert box!
21
Alternative for Including JavaScript Code
  • ltscript language"JavaScript" src"submitExample.j
    s" gt
  • lt/scriptgt
  • Demo http//cs.franklin.edu/brownc/461/submitExa
    mpleWithSRC.html
  • Benefits
  • Can share JavaScript source among many pages
  • Removes a lot of clutter from the page improves
    readability
  • Becomes really important with servlet- and
    JSP-generated pages!
  • Helps to separate page design and functionality
  • Hides your JavaScript code from the casual
    observer
  • But, of course, one can always access the .js
    file separately.
  • There are techniques for encrypting the
    JavaScript file, but we wont go into them.

Still need the end tag
22
Getting the values of form fields
Type of ltinputgt Attribute Attribute Values
checkbox or radio checked true or false
checkbox or radio 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 N/A N/A
ltselectgt selectedIndex 0-based number of the ltoptiongt that is selected
ltselectgt optionsindex.value the value to be submitted
lttextareagt value the text to be submitted
23
Special Code for Accessing Radio Buttons
  • Recall, the radio buttons that work as a group
    are given the same name
  • Thus, JavaScript uses an array to represent them
  • var radioGroup form.userRating
  • var rb
  • var valueChecked ""
  • for(rb 0 rb lt radioGroup.length rb)
  • if(radioGrouprb.checked)
  • valueChecked radioGrouprb.value
  • alert("The value checked is " valueChecked)
  • if(valueChecked "bad") unfair validation!
  • return false
  • return true

An array of all the elements with the name
userRating
Java-style for statement
Arrays have a built-in length property.
Demo http//cs.franklin.edu/brownc/461/submitExa
mpleWithRadio.html
24
Exercise
  • Given a page with 3 radio buttons, add a
    validation function to ensure that one is
    selected. (Well work together as a class.)
  • Starting point http//cs.franklin.edu/brownc/461
    /InClassValidationRadio.html

25
Validation Upon Field Change
  • Check validation as soon as user changes a field
  • Benefit more convenient for user to know of
    error right away
  • Problems
  • Cant check for required fields
  • Wont 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

26
Validation Upon Field Change, cont.
  • onchange event occurs
  • field is losing focus
  • but only if its value has changed
  • ltinput typecheckbox nameopt1
  • onchangevalidate(this) gt
  • lttextarea cols30 rows10 namecomment
  • onchangevalidate(this) gt

27
The onchange Event
  • Event occurs on a form field.
  • The this variable refers to the field, not the
    form
  • You have the choice of
  • 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)
  • 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

28
Example Verify a 5 Digit Zip Code
Note Use the keyboard double quote
character. These open and close quotes are an
artifact of PowerPoint
  • ltinput typetext namezipcode
    onChangevalidate5Zip(this) gt
  • function validate5Zip(field)
  • //verify its a 5-digit zip code
  • var zip field.value
  • if(zip.length ! 5 isNaN(parseInt(zip))
  • alert(please enter a 5 digit zip code.)
  • return false
  • return true

Converts string to integer and checks if result
is not a number
29
Example Recast as a Single Validation Function
ltinput typetext namezipcode
onchangevalidate(this) gt
  • The validate function
  • function validate(field)
  • var val field.value
  • switch(field.name)
  • case "zipcode"
  • if(val.length ! 5 isNaN(parseInt(val))
  • alert(please enter a 5 digit zip code.)
  • return false
  • break
  • case //Other fields tested here
  • return true

Note the switch statement works with strings!
30
A Few More JavaScript Details
  • Emphasizing Differences from Java

31
Accessing Object Properties
  • Properties are somewhat like class members in
    Java
  • Reference properties in 2 ways
  • var txtfld obj.userName
  • var txtfld obj"userName"
  • Properties can be added dynamically
  • obj.myOwnProperty 92

Only valid when property name is alphanumeric,
starting with letter.
Any format of property name Think array with
non-numerical indices
Creates myOwnProperty if its not already present
32
Strings
  • Strings can be concatenated with the operator
  • var s "My name is " theName
  • Most values can be converted automatically to
    strings
  • var n 7
  • var s "The number is " n
  • Strings have a property called length
  • Not a length() method as in Java

33
String Functions
  • Strings have many built-in functions. Here are a
    few examples
  • charAt(n) get the nth character (0 based)
  • var i name.charAt(3) //get 4th character in
    name
  • indexOf(substring, n) search for the substring
    in the string and return its index (0-based
    character number)
  • n is optional and indicates where to start
    looking
  • 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

Returns a string, not a character
34
Arrays
  • Arrays are objects that have properties whose
    names are integer numbers
  • Must use the notation, not the . notation
  • Special length property gives the number of
    elements (mostly)
  • var s ""
  • var radios form.choices
  • for(var r 0 r lt radios.length r)
  • s s " " radiosr.value
  • var firstRadio radios0

The name of the radio group
35
Quotes in JavaScript and HTML
  • 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.".
  • Inside a single-quoted string, use double quotes
    to enter a nested quote
  • var message 'Please see "Instructions"'
  • Quotes can also be escaped with \
  • var message "Please see \"Instructions\""
  • Not recognized by HTML attributes

36
If Statements
  • In Java, the expression inside the if() must be
    of type boolean
  • In JavaScript, any type of expression is
    converted to a Boolean value if possible
  • 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

37
Looping Statements
  • while statement like Java
  • for statement like Java, except
  • for(x in a)
  • 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.elementsx.value )

elements is a property of the form element that
is a collection of all the forms elements
38
Functions
  • Named functions
  • function myFunction(a, b)
  • Accessed as
  • var value myFunction(4, "Hello)
  • Anonymous functions
  • myObject.aFunction function(a, b)
  • Accessed as
  • var otherValue myObject.aFunction(9, 0)

Creates a function that is a method of the
object
39
Regular Expression Matching
  • Fancier Validation

40
Regular Expression Patterns in JavaScript
  • /hello/ ? matches hello
  • /jbsunk/ ? matches junk, bunk, or sunk
  • /\d/ -- matches a digit
  • /abc/ ? matches an a and a c with zero or
    more bs between them
  • /abc/ ? matches an a and a c with one or
    more bs 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
  • /largemediumsmall/ ? matches any of the 3 words

41
Selected Summary of the Pattern Syntax
  • 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 ab matches a or b
  • See pages 342, 343 in Anderson-Freed.

42
A Zip Code Pattern
  • To match 5 or 9 digit zip codes
  • /\d5(-\d4)?/

Match must end at the end of the string
Match must start at the beginning of the string
Matches exactly 5 digits
Makes the dash and 4 digits optional
Matches a dash followed by 4 digits
43
Regular Expression Demo
  • http//cs.franklin.edu/brownc/461/regexpdemo.html

44
Using Patterns in JavaScript Code
  • The String method search(pattern)
  • returns the numerical index of the substring
    matching the pattern
  • returns -1 if there is no match.
  • if(zip.search( /\d5(-\d4)?/ ) -1)
  • alert(Please enter a 5 or 9 digit zip code)

45
Using Patterns in JavaScript Code, alt.
  • The String method match(pattern)
  • returns an object describing the match
  • returns null if there is no match
  • if( !zip.match( /\d5(-\d4)?/ ) )
  • alert(Please enter a 5 or 9 digit zip code)

null evaluates to false
46
5 or 9 Digit Zip Code Field Validation Function
  • function validateZip(field)
  • var zip field.value
  • if( zip.search( /\d5(-\d4)?/ ) -1 )
  • alert("Please enter a 5 or 9 digit zip code.")
  • return false
  • return true

47
Some regular expression references
  • http//www.jansfreeware.com/articles/regexpress.ht
    ml
  • http//www.visibone.com/regular-expressions/

48
Additional Topics
49
onsubmit Validation Combined with onchange
Validation
  • Re-validate fields with onchange validation in
    case they remain unchanged from a default value
  • Invoke the onchange validation function used in
    the onsubmit handler
  • Avoid duplicated code.
  • function check(form)
  • if(!validateZip(form.zip59) )
  • return false
  • if(!form.c1.checked)
  • alert("The checkbox is ")
  • return false
  • return true

Sidebar Be careful of alerts and other messages
when you invoke a validation function from inside
another. Avoid duplicate warnings and other
annoying behavior.
Check for required fields
50
Cross-Field Validation
  • When one fields validation depends on the value
    of another field
  • In onsubmit validation, theres no new problem
    since the form object is passed as a parameter
  • In onchange validation, you access the form
    object through the fields form property
  • function validateShipAddress(field)
  • var isSameAddress field.form.sameAddressCheck.ch
    ecked
  • if(!isSameAddress) //if user hasnt 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

51
Next Weeks Assignment
  • http//cs.franklin.edu/Syllabus/comp461/assignment
    s.htmlvalidation
  • In Registration Page
  • 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
  • Normally validation of all fields would occur. I
    do not require you to repeat the work done on the
    Registration Page.

52
Next Topic
  • 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
Write a Comment
User Comments (0)
About PowerShow.com