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
COMP/DCOM 461 –CWB 2
User Input
Validation
Browser
Server
Form
JavaScript
Validation Code
Validation
Request
Validation
Result
POST or GET
Response Page
Active Server-side
Code
Database
Validation
Update
Java, Perl, etc.
Client-side
Validation
Server-side
Validation
COMP/DCOM 461 –CWB 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)
COMP/DCOM 461 –CWB 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
COMP/DCOM 461 –CWB 5
JavaScript
Scripting language designed for use in
client-sideprogramming 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/standards/Ecma-262.htm
COMP/DCOM 461 –CWB 6
Primary Differences from
Java
No strong typing
The typeof variables are not declared
A variable’s 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
Continued …
Inheritance: use
a prototype for
the prototype
COMP/DCOM 461 –CWB 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 objectsreferring to the
browser window and its various sub-objects
COMP/DCOM 461 –CWB 8
Objects in a Page
Window
HTML document
A form
A text field
A checkbox
As appearing on the
screen
window
document
form
text checkbox
As appearing in the JavaScript
Document Object Model
COMP/DCOM 461 –CWB 9
The Browser Invoking
JavaScript Code
Find Object Corresponding
To User Operation
Event Handler
Defined?
Execute JavaScript for
the Event Handler
Return
Value
Normal Behavior for
the User Action
User Performs Some Action
Done
true
Yes
Such as clicking,
typing, etc.
false
COMP/DCOM 461 –CWB 10
Setting an Event Handler
<form id="myForm" method="get" action="…"
onsubmit="return check(this)" >
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 thisrefers 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.
COMP/DCOM 461 –CWB 11
How Do We Define the
Function check?
<script language="JavaScript">
<!--
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;
}
//-->
</script>
Put this code in the <head>
It will also work in the
<body>, but in the <head>
is preferred.
The <script>tag “hides”
the text inside it from HTML
parsing
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 JavaScript
code can be read in from a
file –discussed later.
What does this code mean?
COMP/DCOM 461 –CWB 12
Defining a Function
<script language="JavaScript">
<!--
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;
}
//-->
</script>
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
“txtFld” and initializes it
•No type is declared for the variable
•The varis optional, but serves to
make the variable local, thus preventing
collisions with variables called “txtFld”
that might be used elsewhere
•formcontains 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. It’s
unnecessary and doesn’t
appear on subsequent
slides.
COMP/DCOM 461 –CWB 13
Defining a Function
<script language="JavaScript">
<!--
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;
}
//-->
</script>
form.t1.valuerefers to the value of the
text field named t1.
•This tests whether the text field’s value
is the empty string.
•The attributes of a tag will appear as
properties of the object associated with
the object.
•Note that string comparisonis done
with the ==operator (unlike Java)
COMP/DCOM 461 –CWB 14
Defining a Function
<script language="JavaScript">
<!--
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;
}
//-->
</script>
The alertfunction is built in
•The alertfunction 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.
The checkfunction returns false.
•This tells the browser to notcontinue
with the submit.
COMP/DCOM 461 –CWB 15
Defining a Function
<script language="JavaScript">
<!--
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;
}
//-->
</script>
This tests if the checkbox is checked or
not.
•The checkedattribute 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.
COMP/DCOM 461 –CWB 16
Defining a Function
<script language="JavaScript">
<!--
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;
}
//-->
</script>
Again there is a popup alert box and the
function returns false to indicate that the
submit should not occur.
The check function returns trueif
everything is OK. This causes the
submit to actually occur.
COMP/DCOM 461 –CWB 17
HTML for a Submit
Example
<html>
<head>
<title>Submit Example</title>
<script language="JavaScript">
</script>
</head>
<body>
<form id="myForm" method="get"
action="javascript:alert('submitted')"
onsubmit="return check(this);" >
<input type="text" name="t1" >
<input type="checkbox" name="c1" value="c1" >
<input type="submit" >
</form>
</body>
</html>
JavaScript from
previous slides
goes here.
Temporary
action URL for
testing
COMP/DCOM 461 –CWB 18
The javascriptURL
Scheme
action="javascript:alert('submitted')"
The URL uses javascriptinstead of httpfor the
scheme.
This is understood by the browser to mean
Don’t send a getrequest 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(<expression>)
This technique can be very useful for debugging and
testing –and sometimes useful for production as
well.
Notice the use of single
quotes inside double quotes
COMP/DCOM 461 –CWB 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)
COMP/DCOM 461 –CWB 20
What Have We Done So
Far?
Added an onsubmitattribute to the <form>tag that
calls the check function, passing a reference to the
form by using the thiskeyword.
Defined the checkfunction in a <script>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/submitExample.html
Comment on demo: It would be better to
list allerrors at once in the alert box!
COMP/DCOM 461 –CWB 21
Alternative for Including
JavaScript Code
<script language="JavaScript" src="submitExample.js" >
</script>
Demo: http://cs.franklin.edu/~brownc/461/submitExampleWithSRC.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 casualobserver
But, of course, one can always access the .js file separately.
There are techniques for encrypting the JavaScript file, but we won’t
go into them.
Still need the end tag
COMP/DCOM 461 –CWB 22
Getting the values of
form fields
Type of
<input>
Attribute Attribute Values
checkbox or radio checked 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
N/A N/A
<select> selectedIndex 0-based number of the <option>
that is selected
options[index].value
the value to be submitted
<textarea> value the text to be submitted
COMP/DCOM 461 –CWB 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 arrayto represent
them:
var radioGroup = form.userRating;
var rb;
var valueChecked = "";
for(rb = 0; rb < radioGroup.length; rb++)
if(radioGroup[rb].checked)
valueChecked = radioGroup[rb].value;
alert("The value checked is: " + valueChecked);
if(valueChecked == "bad") #unfair validation!
return false;
return true;
}
Arrays have a
built-in length
property.
An arrayof all the elements
with the name userRating
Demo: http://cs.franklin.edu/~brownc/461/submitExampleWithRadio.html
Java-style
for
statement
COMP/DCOM 461 –CWB 24
Exercise
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/InClassValidationRadio.html
COMP/DCOM 461 –CWB 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:
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
fieldsare changed
Can be annoying if done clumsily
COMP/DCOM 461 –CWB 26
Validation Upon Field
Change, cont.
onchangeevent occurs
field is losing focus
but only if its value has changed
<input type=“checkbox” name=“opt1”
onchange=“validate(this)” >
<textarea cols=“30” rows=“10” name=“comment”
onchange=“validate(this)” >
COMP/DCOM 461 –CWB 27
The onchangeEvent
Event occurs on a form field.
The thisvariable 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 ifits value has changed
Gives you the ability to tell users of errors
immediately
COMP/DCOM 461 –CWB 28
Example: Verify a 5 Digit
Zip Code
<input type=“text” name=“zipcode”
onChange=“validate5Zip(this)” >
function validate5Zip(field)
{ //verify it’s 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”
Note: Use the
keyboard double
quote character.
These open and
close quotes are
an artifact of
PowerPoint
COMP/DCOM 461 –CWB 29
Example Recast as a Single
Validation Function
Thevalidatefunction:
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;
}
<input type=“text”
name=“zipcode”
onchange=“validate(this)”
>
Note the
switch
statement
works with
strings!
30
A Few More JavaScript Details
Emphasizing Differences from
Java
COMP/DCOM 461 –CWB 31
Accessing Object
Properties
Properties are somewhat like
class members in Java
Reference properties in 2 ways:
1.var txtfld = obj.userName;
2.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 it’s not already present
COMP/DCOM 461 –CWB 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 propertycalled length
Not a length() method as in Java
COMP/DCOM 461 –CWB 33
String Functions
Strings have many built-in functions. Here are a fewexamples:
charAt(n)–get the n
th
character (0 based)
var i = name.charAt(3); //get 4th character in name
indexOf(substring, n) –search for the substringin the string
and return its index (0-based character number)
nis 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
COMP/DCOM 461 –CWB 34
Arrays
Arrays are objects that have properties
whose names are integer numbers
Must use the [ ]notation, not the .
notation
Special lengthproperty gives the number
of elements (mostly)
var s = "";
var radios = form.choices;
for(var r = 0; r < radios.length; r++)
s = s + " " + radios[r].value;
var firstRadio = radios[0];
The name of the
radio group
COMP/DCOM 461 –CWB 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\"";
Notrecognized by HTML attributes
COMP/DCOM 461 –CWB 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
COMP/DCOM 461 –CWB 37
Looping Statements
whilestatement: like Java
forstatement: like Java, except …
for(x ina)
Automatically iterates through an array or through
the properties of an object
In each iteration, x is set to the array indexor the
nameof the property
for(x in form.elements)
alert("Element " + x + "'s value is "
+ form.elements[x].value ); elements is a property
of the form element
that is a collection of all
the form’s elements
COMP/DCOM 461 –CWB 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
COMP/DCOM 461 –CWB 40
Regular Expression
Patterns in JavaScript
/hello/matches “hello”
/[jbs]unk/matches “junk”, “bunk”, or “sunk”
/\d/--matches a digit
/ab*c/matches an “a” and a “c” with zeroor more “b”s
between them
/ab+c/matches an “a” and a “c” with oneor 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 41
Selected Summary of the
Pattern Syntax
An itemis 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 42
A Zip Code Pattern
To match 5 or 9 digit zip codes:
/^\d{5}(-\d{4})?$/
Matches
exactly 5
digits
Matches a
dash followed
by 4 digits
Makes the
dash and 4
digits optional
Match
must start
at the
beginning
of the
string
Match
must end
at the end
of the
string
COMP/DCOM 461 –CWB 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( /^\d{5}(-\d{4})?$/ ) == -1)
{
alert(“Please enter a 5 or 9 digit zip code”);
}
COMP/DCOM 461 –CWB 45
Using Patterns in
JavaScript Code, alt.
The String method match(pattern)
returns an object describing the match
returns nullif there is no match
if( !zip.match( /^\d{5}(-\d{4})?$/ ) )
{
alert(“Please enter a 5 or 9 digit zip code”);
}
null
evaluates
to false
COMP/DCOM 461 –CWB 46
5 or 9 Digit Zip Code
Field Validation Function
function validateZip(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 47
Some regular expression
references
http://www.jansfreeware.com/articles/regexpress.html
http://www.visibone.com/regular-expressions/
48
Additional Topics
COMP/DCOM 461 –CWB 49
onsubmit Validation Combined
with onchange Validation
function check(form)
{
if(!validateZip(form.zip59) )
return false;
if(!form.c1.checked)
{
alert("The checkbox is …");
return false;
}
return true;
}
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.
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
COMP/DCOM 461 –CWB 50
When one field’s validation depends on the value of another field:
In onsubmit validation, there’s no new problem since the formobject is passed
as a parameter
In onchange validation, you access the formobject through the field’s form
property:
function validateShipAddress(field)
{
var isSameAddress = field.form.sameAddressCheck.checked;
if(!isSameAddress) //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;
}
Cross-Field Validation
COMP/DCOM 461 –CWB 51
Next Week’s Assignment
http://cs.franklin.edu/Syllabus/comp461/assignments.html#validation
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.
COMP/DCOM 461 –CWB 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