Tuesday, June 26, 2007

JavaScript Validation

JavaScript History
• Java was born as “LiveScript” at the beginning of the
94’s.
• Name changed into JavaScript (name owned by
Netscape)
• Microsoft responds with Vbscript
• Microsoft introduces JScript (dialect of Javascript)
• A standard is defined: ECMAScript (ECMA-262,
ISO-16262)
2
2
J0
3
JavaScript Myths
JavaScript is NOT simple
Simple tasks are indeed simple
JavaScript is NOT Java
Graphics YES Partial
Networking YES NO
Browser Control NO YES
Java JavaScript
J0
4
JavaScript is…
Scripted (not compiled)
Powerful
Object-based
Cross-Platform
Client and Server
3
3
J0
5
JavaScript allows…
DynamicWeb Sites
Dynamic HTML (DHTML)
Interactive Pages/Forms
Server-Side CGI Functionality
Application Development
J0
6
JavaScript can…
Build Objects
Use Events
Enforce Security
Embed or Componentize
4
4
J0
7
Base
• Syntax is C-like (C++-like, Java-like)
case-sensitive,
statements end with (optional) semicolon ;
//comment /*comment*/
operators (=,*,+,++,+=,!=,==,&&,…)
• Basic data types
integer, floating point, strings (more later)
• Loosely typed variables (Basic-like) var x=3;
Core Core
J0
8
Statements
• if (expression) {statements} else {statements}
• switch (expression) {
case value: statements; break;

default: statements; break;
}
• while (expression) {statements}
• do (expression) while {statements}
• for (initialize ; test ; increment) {statements}
Core Core
5
5
J0
9

10
Strings
a=“foo”; b=‘tball’

indexOf(substring), lastIndexOf(substring)
charCodeAt(n),fromCharCode(value,…)
concat(value,…),slice(start,end)
toLowerCase(), toUpperCase()
replace(regexp,string), search(regexp)
Core Core
6
6
J0
11
Strings
a=“foo”;
TAG-related methods:
a.bold() => foo
big(), blink(), fontcolor(), fontsize(), small(),
strike(), sup()
anchor(),link()
Core Core
J0
12
Functions
function f(x) {return x*x}
_____________________________________________
function add(x,y) {return x+y};
function multiply(x,y) {return x*y};
function operate(op,x,y) {return op(x,y)};
operate(add,3,2); => 5
Core Core



Objects
Object: A data structure with methods;
a special method is the “constructor”.
function Rectangle(w, h) {
this.width=w;
this.height=h;
this.area=function(){return this.width*this.height}
}
a=new Rectangle(3,4); a.area() => 12 a.width => 3
Instance variables
method
Core Core
9
9
J0
17
Objects
Actually, JavaScript does NOT have classes and inheritance.
Moreover, the approach we have shown is not the most
efficient in terms of memory allocation.
It would be better to use the “prototype” feature, which can
be consideres a STATIC object
Rectangle.prototype.area=function(){return this.w*this.h}
Core Core
J0
18
Arrays
a = new Array()
a[0]=3; a[1]=“hello”; a[10]=new Rectangle(2,2);
a.length() => 11
Arrays can be
SPARSE, INHOMOGENEOUS , ASSOCIATIVE
a[“name”]=“Jaric”
z=new Rectangle(3,4); z[“width”] z.width
Core Core
10
10
J0
19
Object hierarchy
DOM DOM
frames[] history
anchors[] applets[] embeds[]
Button Checkbox Form Hidden
Input Password Radio Reset
Select Submit Text Textarea
elements[]
forms[] links[] plugins[] images[]
document location navigator screen parent top
Window
The Most
Important Slide
Symbol means containment (has-a)
Dashed line means “is an instance of”
J0
20
Window
Other properties
status – defaultStatus
name
Main properties
Objects
history
frames[]
document
location
navigator
screen
parent – top
“A web browser window or frame”
DOM DOM
11
11
J0
21
Window
Main methods
alert(), prompt(), confirm()
focus(), blur()
moveBy(), moveTo()
resizeBy(), resizeTo()
scroll(), scrollBy(), scrollTo()
setInterval(), clearInterval()
setTimeout(), clearTimeout()
DOM DOM
J0
22
Screen
Main properties
availHeight, availWidth
height, width
colorDepth, pixelDepth
hash
“Information about the display”
DOM DOM
12
12
J0
23
Navigator
Main methods
javaEnabled()
Other properties
Info on available plugins, but only in Netscape
Navigator!
Main properties
appName
appVersion
Platform
“Information about the browser in use”
DOM DOM
J0
24
History
Main methods
back()
forward()
go(+/-n)
go(target_substring)
Main properties
lenght
“The URL history of the browser”
DOM DOM
13
13
J0
25
Location
Main methods
reload()
replace()
Main properties
href
protocol, hostname, port
search
hash
“The specification of the current URL”
DOM DOM
J0
26
Document
Main methods
open()
close()
clear()
write()
Other properties
bgColor, fgColor, linkColor, vlinkColor
lastModified
title, URL, referrer, cookie
Main properties
Arrays of Component Objects
anchors[]
applets[]
embeds[]
forms[]
links[]
plugins[]
“An HTML document”
DOM DOM
14
14
J0
27
Image
Main properties
border [width in pixels]
height
width
src [URL of the image to be displayed]
“An image embedded in an HTML document”
DOM DOM
J0
28
Events
Document, Image, Link,
Text elements
onKeyPress KeyDown+KeyUp (*)
Document, Image, Link,
Text elements
onKeyUp User releases key
Document, Image, Link,
Text elements
onKeyDown User presses key (*)
onMouseOut Mouse moves off element Link, Image, Layer
onMouseOver Mouse moves over element Link, Image, Layer
Document, Image, Link,
button
onMouseUp User releases mouse button (*)
Document, Image, Link,
button
onMouseDow User presses mouse button (*)
n
Document, Image, Link,
button
onDblClick User clicks twice
onClick User clicks once. (*) Link, button
(*) Return false to cancel default action
DOM DOM
15
15
J0
29
Events
onResize Window is resized Window
onSubmit Form submission requested(*) Form
onReset Form reset requested (*) Form
onUnload Document is unloaded Window
Document or image finishes Window, Image
loading
onLoad
onAbort Loading interrupted Image
onError Error while loading image Image
User selects/deselects a text Select, text input elements
and moves focus away
onChange
TextElement, Window, all
form elements
onBlur Element loses focus
TextElement, Window, all
form elements
onFocus Element gains focus
(*) Return false to cancel default action
DOM DOM
J0
30
Input
Hidden X X X X
Select X X X X X X X X X X X X
FileUpload X X X X X X X X X X X
Password X X X X X X X X X X X
Textarea X X X X X X X X X X X
Text X X X X X X X X X X X
Submit X X X X X X X X X X
Reset X X X X X X X X X X
Radio X X X X X X X X X X X X
Checkbox X X X X X X X X X X X X
Button X X X X X X X X X X
defaultChecked
checked
defaultValue
form
length
name
options[] selectedIndex
type value
blur()
click()
focus()
select()
onblur
onchange
onclick
onfocus
Methods
Event
Handlers
Properties
Properties
Objects
DOM DOM
16
16
J0
31
Form
Main properties
action [destination URL]
method [get/post]
name [name of Form]
name [destination Window]
Elements[] [list ;of contained elements]
Main methods
reset()
submit()
“An HTML input form”
DOM DOM
J0
32



A more complex example -3
function isEmpty(s)
{ return ((s == null) || (s.length == 0))
}
function warnEmpty (theField, s)
{
var mPrefix = "You did not enter a value into the ";
var mSuffix = " field. This is a required field. Please enter it now.";
theField.focus();
alert(mPrefix + s + mSuffix);
return false;
}
Check that the string
“s” is not empty
Issue a warning
message
All this is contained in the file “FormCheck.js”
19
19
J0
37
A more complex example -4
function promptEntry (s)
{ window.status = "Please enter a " + s;
}
function validatePersonalInfo(form)
{ return (
checkString(form.elements["LastName"],sLastName)
)
}
function checkString (theField, s)
{
if (isEmpty(theField.value)) return warnEmpty (theField, s);
else return true;
}
Type a message in the status bar
Check that “theField”
is not empty
Validate the form
(should run over all fields
And perform suitable checks)
All this is contained in the file “FormCheck.js”
J0
38



Applet
Methods
Same as the public methods
of the Java applet
Properties
Same as the public fields
of the Java applet
“An applet embedded in a Web page”
DOM DOM
J0
42
LiveConnect
A two-faced, (Netscape-only) technology to let JavaScript
interact with Java, so that:
• A JavaScript script can control and coordinate Java
applets, and let Java applets interact with plugins.
• A Java Applet can execute JavaScript code.
22
22
J0
43
Server-Side JavaScript
Not discussed here!
A substitute for CGI.
Server-dependent technology to process the
Web page before passing it to the client.
(The Netscape SSJS object model is different from the
Microsoft ASP object model, although JavaScript can
be used as SSLanguage for ASP)
See
http://developer.netscape.com/viewsource/husted_js/husted_js.html
J0
44
References
Standard ECMA-262 ECMAScript Language Specification:
http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM ()
Tutorials and references:
• http://developer.netscape.com/tech/javascript/javascript.html
• http://www.sauronsoftware.it/jsreference
Books:
• D.Flanagan “Javascript. The definitive guide” O’Reilly.
• D.Goodman “Dynamic HTML. The definitive reference” O’Reilly
23
23
J0
45
Java-JavaScript interaction: JSObject
JSObject allows Java to manipulate objects that are defined in JavaScript.
Values passed from Java to JavaScript are converted as follows:
JSObject is converted to the original JavaScript object.
Any other Java object is converted to a JavaScript wrapper, which can be
used to access methods and fields of the Java object.
Converting this wrapper to a string will call the toString method on the
original object, converting to a number will call the floatValue method if
possible and fail otherwise.
Converting to a boolean will try to call the booleanValue method in the
same way.
Java arrays are wrapped with a JavaScript object that understands
array.length and array[index].
A Java boolean is converted to a JavaScript boolean.
Java byte, char, short, int, long, float, and double are converted to
JavaScript numbers.
Note If you call a Java method from JavaScript, this conversion happens
automatically--you can pass in "int" argument and it works.
J0
46
Java-JavaScript interaction: JSObject
Values passed from JavaScript to Java are converted as follows:
Objects that are wrappers around Java objects are unwrapped.
Other objects are wrapped with a JSObject.
Strings, numbers, and booleans are converted to String, Float, and
Boolean objects respectively.
Examples
(String) window.getMember("name")
(JSObject) window.getMember("document")
24
24
J0
47
Java-JavaScript interaction: JSObject
The netscape.javascript.JSObject class has the following methods:
Method Description
Call Calls a JavaScript method
Eval Evaluates a JavaScript expression
getMember Retrieves a named member of a JavaScript object
getSlot Retrieves an indexed member of a JavaScript object
removeMember Removes a named member of a JavaScript object
setMember Sets a named member of a JavaScript object
setSlot Sets an indexed member of a JavaScript object
toString Converts a JSObject to a string
The netscape.javascript.JSObject class has the following static methods:
getWindow Gets a JSObject for the window containing the given applet
J0
48
Java-JavaScript interaction: applet
side
package javascript;
import netscape.javascript.*;
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
private JSObject mainWindow;
private JSObject pageDoc;
private JSObject location;
private String s;
public String comment="instanceVarContent";
public void init() {
System.out.println("initing");
mainWindow = JSObject.getWindow(this);
pageDoc = (JSObject) mainWindow.getMember("document");
location = (JSObject) mainWindow.getMember("location");
s = (String) location.getMember("href"); // document.location.href
}
25
25
J0
49
Java-JavaScript interaction: applet
side
public int r=0;
public int g=255;
public int b=0;
public void start(){
s=(String)mainWindow.call("f",null);
String[] stringArgs = new String[1];
stringArgs[0] = "5";
s=(String)mainWindow.call("g", stringArgs);
System.out.println (" Calling g returned "+s);
}
public void paint(Graphics gra) {
if (s==null) s="NULL";
gra.setColor(new Color(r,g,b));
Dimension d=this.getSize();
gra.fillRect(0,0,d.width,d.height);
gra.setColor(new Color(0,0,0));
gra.drawString("VERSION 1",80,80);
gra.drawString(s,30,30);
}
J0
50
Java-JavaScript interaction: applet
side
void changeColor(String s) {
int x=Integer.parseInt(s);
r=x;
this.repaint();
}
public String square(String sx) {
int x=Integer.parseInt(sx);
return new Integer(x*x).toString();
}
}
26
26
J0
51

No comments: