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 2010 Marty Stepp and Jessica Miller.

Valid XHTML 1.1 Valid CSS!

A form that submits to itself

<form action="" method="post">
	...
</form>

Processing a self-submitted form

if ($_SERVER["REQUEST_METHOD"] == "GET") {
	# normal GET request; display self-submitting form
	?>
	<form action="" method="post">...</form>
	<?php
} elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
	# POST request; user is submitting form back to here; process it
	$var1 = $_REQUEST["param1"];
	...
}

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) {
	print "Error, invalid city/state/zip submitted.";
}

Regular expressions

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

Basic regular expressions

/abc/

Wildcards: .

Special characters: |, (), \

Quantifiers: *, +, ?

More quantifiers: {min,max}

Anchors: ^ and $

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 given regex as delimiter (like 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)) {
	print "Error, invalid state submitted.";
}