http://www.developer.com/services/article.php/3848276/Forms-Processing-with-the-Zend-Framework.htm
One of the key reasons for the meteoric rise of the World
Wide Web is that unlike television, radio, or the
traditional newspaper, it offers an immediate conduit for
two-way communication. Yet many Web developers, particularly
those with relatively little experience, seem to place
remarkably little emphasis on devising efficient methods for
accepting and processing user-provided information. Much of
the reason for such oversight is due to complexity;
effectively validating a complex string such as an e-mail
address, or ensuring that a password is of a certain length
are programmatic tasks which can strain the boundaries of
many beginning developers' knowledge. Additionally,
developers need to understand how to effectively respond to
errors which crop up in the validation process, whether it's
providing the user with error-specific feedback, or
repopulating the form in order to not discourage the errant
user from correcting his errors and submitting the form
anew. Given the universal challenge forms processing presents
to Web developers no matter the project, it's no wonder that
implementing an efficient forms processing solution is often
high on the priority list of most Web framework developers.
The Zend Framework is no different, offering developers a
powerful solution for not only validating forms data, but
actually programmatically building the form HTML. In this
tutorial I'll introduce you to the Zend Framework's
validation feature, showing you how easy it is to not only
validate user provided data with confidence, but also how to
inform the user of the error should validation fail. These days most serious Web sites provide the visitor
with an opportunity to become a registered user in order to
access restricted material or customized content. Because
the number of registered users is often directly
proportional to a Web site owner's income, it's crucial for
the registration step to be streamlined and convenient in
order to give the visitor every incentive to complete the
process. Although you should keep the required registration
fields to a minimum in order to provide the user with the
shortest path to completion, the validation necessary to vet
the data often goes beyond merely determining whether a
field was left blank. Figure 1 presents what such a
registration form might look like.
Although consisting of just five fields, validating this
form presents several challenges:
Using the Zend Framework's To validate the fields, first you'll invoke the
Next you'll call the
As I mentioned, the Zend_Validate component's
capabilities go well beyond merely checking a value for
existence. For instance, to validate an e-mail address, you
can both ensure the value is not blank and that it meets the
requirements as defined by RFC 2822 by invoking the
EmailAddress class:
Although it's possible to invoke each validation class as
needed, you can use a very convenient static method named
When an error occurs, the
This isn't exactly an ideal message, if for any other
reason because it doesn't tell the user precisely which
value is required and can't be empty. You can override the
default messages
Next, rather than output the error messages using a
Finally, to present the errors in a well-organized
fashion, I like to use a custom view helper which can be
repeatedly used throughout the Web site as desired:
Within the view, you can call the helper like this:
After some CSS styling, attempting to submit the form
with a blank name will produce the error message shown in
Figure 2.
Of course, chances are your form will contain multiple
fields, such as the aforementioned registration form.
Because you'll need to validate each field, it's possible
that several errors could crop up. You'll need to keep track
of all errors and present them to the user. To do this, I
like to eliminate the need to use the
Processing user input is such a commonplace task within
Web sites of all sizes and purposes, that there's really no
excuse to not rely upon a well-organized approach such as
the one offered by the Zend Framework. In fact, forms
processing is so important that the framework actually
offers quite a bit more functionality than what has been
introduced in this tutorial. Check out the following links
for more information!
Jason Gilmore is founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites
with the Zend Framework". Formerly Apress' open source
editor, Jason fostered the development of more than 60
books, along the way helping to transform their open source
line into one of the industrys most respected publishing
programs. Over the years he's authored several other books,
including the best-selling Beginning PHP
and MySQL: From Novice to Professional (currently in its
third edition), Beginning PHP
and PostgreSQL: From Novice to Professional, and Beginning PHP
and Oracle: From Novice to Professional. Jason is a cofounder and speaker chair of CodeMash, a nonprofit
organization tasked with hosting an annual namesake
developers conference, and was a member of the 2008 MySQL
Conference speaker selection board. Jason has published more than 100 tutorials and articles
within prominent publications such as Developer.com, Linux Magazine, and TechTarget.
Forms Processing with the Zend Framework
November 23, 2009
Introduction
Introducing the Zend_Validate Component

Figure 1. A Web site registration form
Zend_Validate
component, carrying out these field validations is a trivial
process. Zend_Validate offers developers an
extensive suite of validation procedures capable of ensuring
data meets a wide variety of specifications, such as whether
a number falls within a certain range, a credit card is
valid as defined by the Luhn algorithm, or a value falls
within a predefined list of valid values as defined by
elements within an array. These procedures are packaged
within the component as a number of different classes, with
each class serving a specific validation purpose. See this
page of the Zend Framework manual for a complete list of
what's available.Zend_Validate() class, and then add validators
by passing each to the addValidator() class,
like this:
$validator = new Zend_Validate_NotEmpty();
isValid() method,
passing in the field you'd like to validate. If the
isValid() method returns FALSE, you can call
the getMessages() method to retrieve a list of
predefined error messages.
if (! $validator->isValid($this->_request->getPost('name'))) {
echo "The name is not blank";
} else {
foreach($validator->getMessages() as $message) {
echo "{$message}<br />";
}
}
$validator = new Zend_Validate_EmailAddress();
if (! $validator->isValid($this->_request->getPost('email')) {
echo "Please provide your e-mail address.";
}
Streamlining the Validator Invocation Process
Zend_Validate::is() to streamline the
invocation process. For instance, to determine whether a
field is blank, you can invoke the NotEmpty
class like this:
if (! Zend_Validate::is($data['name'], 'NotEmpty')) {
echo "Please provide your name.";
}
Customizing Error Messages
getMessages()
method will retrieve a list of predefined error messages.
However, these messages can be quite terse; For instance, in
the case the Zend_Validate_NotEmpty() validator
determines a value to be empty, the following error message
will be provided:
Value is required and can't be empty
$validator->setMessages(array(Zend_Validate_NotEmpty::IS_EMPTY => "Please provide your name."));
for loop within your controller action (which
would break the MVC paradigm), create an array used to
contain errors, and then assign the
getMessages() return value to it:
$this->view->errors = array();
$this->view->errors = $validator->getMessages();
<?php
class Zend_View_Helper_Errors extends Zend_View_Helper_Abstract
{
public function Errors($errors)
{
echo "<div id='errors'>";
echo "<p>Errors were found:</p>";
echo "<ul>";
foreach ($errors AS $error) {
echo "<li>$error</li>";
}
echo "</ul>";
echo "</div>";
}
}
?>
<?php if (count($this->errors) > 0) { ?>
<?= $this->Errors($this->errors); ?>
<?php } ?>

Figure 2. Displaying an error message
Validating Multiple Fields
getMessages method altogether and just use my
own simple error tracking feature, like this:
$this->errors = array();
if (! Zend_Validate::is($this->_request->getPost('name'), 'NotEmpty')) {
$this->errors[] = "Please provide your name.";
}
if (! Zend_Validate::is($this->_request->getPost('email'), 'EmailAddress')) {
$this->errors[] = "Please provide a valid e-mail address.";
}
if (count($this->view->errors) > 0) {
$this->view->errors = $this->errors;
} else {
// Continue with processing
}
Where to From Here?
About the Author