Web Programming Step by Step, 2nd Edition

Lecture 11: Form Validation

Reading: 15.1 - 15.3

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

What is form validation?

A real form that uses validation


Client vs. server-side validation

Validation can be performed:

An example form to be validated

<form action="http://foo.com/foo.php" method="get">
		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" />

One problem: Users submitting HTML content

The htmlspecialchars function

htmlspecialchars returns an HTML-escaped version of a string
$text = "<p>hi 2 u & me</p>";
$text = htmlspecialchars($text);   # "&lt;p&gt;hi 2 u &amp; me&lt;/p&gt;"

Basic server-side validation code

$city  = $_POST["city"];
$state = $_POST["state"];
$zip   = $_POST["zip"];
if (!$city || strlen($state) != 2 || strlen($zip) != 5) {
	print "Error, invalid city/state/zip submitted.";

Regular expressions


Basic regular expressions


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)

PHP form validation w/ regexes

$state = $_POST["state"];
if (!preg_match("/^[A-Z]{2}$/", $state)) {
	print "Error, invalid state submitted.";

Regular expression PHP 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")