Web Programming Step by Step

Lecture 11
Form Validation

References: PHP.net, webcheatsheet.com, roscripts, PHPro

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

Valid XHTML 1.1 Valid CSS!

What is form validation?

A real form that uses validation

wamu

Client vs. server-side validation

Validation can be performed:

An example form to be validated

<form action="http://foo.com/foo.php" method="get">
	<div>
		City:  <input name="city" /> <br />
		State: <input name="state" size="2" maxlength="2" /> <br />
		ZIP:   <input name="zip" size="5" maxlength="5" /> <br />
		<input type="submit" />
	</div>
</form>

Basic server-side validation code

$city  = $_REQUEST["city"];
$state = $_REQUEST["state"];
$zip   = $_REQUEST["zip"];
if (!$city || strlen($state) != 2 || strlen($zip) != 5) {
	?>
	<h2>Error, invalid city/state submitted.</h2>
	<?php
}

What is a regular expression?

"/^[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}$/"

Basic regular expressions

"/abc/"

Wildcards: .

Special characters: |, (), ^, \

Quantifiers: *, +, ?

More quantifiers: {min,max}

Character sets: []

Character ranges: [start-end]

Escape sequences

Regular expressions in PHP (PDF)

function description
preg_match(regex, string) returns TRUE if string matches regex
preg_replace(regex, replacement, string) returns a new string with all substrings that match regex replaced by replacement
preg_split(regex, string) returns an array of strings from given string broken apart using the given regex as the delimiter (similar to explode but more powerful)

Regular expression example

# replace vowels with stars
$str = "the quick    brown        fox";

$str = preg_replace("/[aeiou]/", "*", $str);
                         # "th* q**ck    br*wn        f*x"

# break apart into words
$words = preg_split("/[ ]+/", $str);
                         # ("th*", "q**ck", "br*wn", "f*x")

# capitalize words that had 2+ consecutive vowels
for ($i = 0; $i < count($words); $i++) {
	if (preg_match("/\\*{2,}/", $words[$i])) {
		$words[$i] = strtoupper($words[$i]);
	}
}                        # ("th*", "Q**CK", "br*wn", "f*x")

PHP form validation w/ regexes

$state = $_REQUEST["state"];
if (!preg_match("/[A-Z]{2}/", $state)) {
?>

	<h2>Error, invalid state submitted.</h2>

<?php
}