intro
Let’s validate submitted data using Zend Form.You can download the source code of this article from here.
1.Create Controller
Create the file
application/constorllers/IndexController.php
with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<?php require_once 'Zend/Controller/Action.php'; require_once 'Zend/Form.php'; class IndexController extends Zend_Controller_Action { public function getProfileForm() { $form = new Zend_Form(); $form->setAction($this->_request->getBaseUrl() . '/index/profile') ->setMethod('post'); $givenName = $form->createElement('text', 'givenName'); $givenName->setLabel('Given Name') ->setRequired(true) ->addFilter('stringTrim') ->addValidator('stringLength', false, array(1,50)); $familyName = $form->createElement('text', 'familyName'); $familyName->setLabel('Family Name') ->setRequired(true) ->addFilter('stringTrim') ->addValidator('stringLength', false, array(1,50)); $email = $form->createElement('text', 'email'); $email->setLabel('E-Mail') ->setRequired(true) ->addFilter('stringTrim') ->addValidator('emailAddress', false); $url = $form->createElement('text', 'url'); $url->setLabel('URL') ->setRequired(false) ->addFilter('stringTrim') ->addValidator('stringLength', false, array(1,100)); $submit = $form->createElement('submit', 'submit'); $submit->setLabel('Send'); $form->addElements(array( $givenName, $familyName, $email, $url, $submit )); return $form; } public function indexAction() { $this->_forward('profile'); } public function profileAction() { $form = $this->getProfileForm(); if ($this->getRequest()->isPost()) { if ($form->isValid($_POST)) { $values = $form->getValues(); $this->view->values = $values; } } $this->view->form = $form; } } |
2.Create View
Create the file
application/views/scripts/error/profile.phtml
with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Zend Framework Quick Start</title> </head> <body> <h1 id="5_basic-blog_1" ><?= $this->translate('Your Profile'); ?></h1> <?php if($this->values) : ?> <h3 id="5_submitted" > <?= $this->translate('You just submitted the following values'); ?>: </h3> <ul> <?php foreach ($this->values as $value) :?> <li> <?= $this->escape($value); ?> </li> <?php endforeach; ?> </ul> <?php else : ?> <?= $this->form; ?> <?php endif; ?> </body> </html> |
3.Check
Let’s access your web server and check how this simple validation program works.