Web Programming Step by Step

Lecture 17
Client-Side Validation

Except where otherwise noted, the contents of this presentation are Copyright 2010 Marty Stepp and Jessica Miller.

Valid XHTML 1.1 Valid CSS!

Page/window events (9.2.5)

namedescription
load, unload the browser loads/exits the page
resize the browser window is resized
error an error occurs when loading a document or an image
contextmenu the user right-clicks to pop up a context menu
window.onload = function() { ... };
document.observe("dom:loaded", function() {
	// attach event handlers, etc.
});

Keyboard/text events (9.2.3)

name description
keydown user presses a key while this element has keyboard focus
keyup user releases a key while this element has keyboard focus
keypress user presses and releases a key while this element has keyboard focus
focus this element gains keyboard focus
blur this element loses keyboard focus
select this element's text is selected or deselected)

Key event objects

property name description
keyCode ASCII integer value of key that was pressed
(convert to char with String.fromCharCode)
altKey, ctrlKey, shiftKey true if Alt/Ctrl/Shift key is being held
Prototype's key code constants
Event.KEY_BACKSPACE Event.KEY_DELETE Event.KEY_DOWN Event.KEY_END
Event.KEY_ESC Event.KEY_HOME Event.KEY_LEFT Event.KEY_PAGEDOWN
Event.KEY_PAGEUP Event.KEY_RETURN Event.KEY_RIGHT Event.KEY_TAB
Event.KEY_UP

Form events (9.1.6, 9.2.4)

event name description
submit form is being submitted
reset form is being reset
change the text or state of a form control has changed
activate clear disable enable
focus getValue present select

Prototype form shortcuts (9.1.6)

$F("formID")["name"]
$F("controlID")

Stopping an event

<form id="exampleform" action="http://foo.com/foo.php">...</form>
window.onload = function() {
	$("exampleform").observe("submit", checkData);
};

function checkData(event) {
	if ($F("city") == "" || $F("state").length != 2) {
		alert("Error, invalid city/state.");  // show error message 
		event.stop();
		return false;
	}
}

Regular expressions in JavaScript

Replacing text with regular expressions

  • string.replace(regex, "text")
    • replaces the first occurrence of given pattern with the given text var str = "Marty Stepp";
      str.replace(/[aeiou]/, "*") returns "M*rty Stepp"
  • a g can be placed after the regex for a global match (replace all occurrences)
    • str.replace(/[aeiou]/g, "*") returns "Mxrty Stxpp"
  • does not modify the string itself; returns the modified string as its result
    str.replace(/[aeiou]/g, "*");       // str still "Marty Stepp" !
    str = str.replace(/[aeiou]/g, "*");   // str now "M*rty St*pp"
  • remove disallowed characters ("filter") by replacing with empty string
    • str = str.replace(/[^A-Z]+/g, "") turns str into "MS"