Zend Framework Model Based Validation Part 1

I’m not really a big fan of Zend_Form, too verbose and less flexible. I’ve been using this little base class for several of my freelance projects. It basically allows you to define validation rules for your model’s columns. This is a very basic version that I’m planning to enhance soon with custom validation functions.

Download version 0.1

USAGE EXAMPLE

Model

<?
class User extends AbstractModelValidator {
	protected $_name = 'users';
	protected $_primary = 'id';
	protected $_rules = array(
		array('name'=>'firstname', 'class'=>'NotEmpty', 'message'=>'Required Field (Firstname)'),
		array('name'=>'firstname', 'class'=>'StringLength', 'options'=>array(0, 50),'message'=>'Max length is 50 (Firstname)'),
		array('name'=>'lastname', 'class'=>'NotEmpty', 'message'=>'Required Field (Lastname)'),
		array('name'=>'lastname', 'class'=>'StringLength', 'options'=>array(0, 50),'message'=>'Max length is 50 (Lastname)'),
	);
}

Controller

<?
class UsersController extends Zend_Controller_Action {
	public function addAction() {
		$this->view->req = $this->_request;
		if($this->_request->isPost()) {
			$u = new User();
			if($u->isValid($this->_request->getParams())) {

			}
			else {
				$this->view->errors = $u->getValidationMessages();
			}
		}
	}
}

View

<html>
	<head>
		<title>Add User</title>
	</head>
	<body>
		<? if(isset($this->errors) && sizeof($this->errors) > 0): ?>
			<ul>
				<? foreach($this->errors as $e): ?>
					<li><?=$e?></li>
				<? endforeach; ?>
			</ul>
		<? endif; ?>
		<div>
			<form action="<?=$this->url()?>" method="post">
				<div>Firstname:</div>
				<div><?=$this->formText('firstname', $this->req->getParam('firstname'), array('size'=>20))?></div>
				<div>Lastname::</div>
				<div><?=$this->formText('lastname', $this->req->getParam('lastname'), array('size'=>20))?></div>
				<div><?=$this->formSubmit('submit', 'Submit')?></div>
			</form>
		</div>
	</body>
</html>

  • Share/Bookmark
3 Comments

3 Comments

  1. Hello Jan!
    Congratulations, this is awesome. I was hating doing validation on Zend_Form, since validation should be ruled by the model.

    Tried your AbstractModelValidator class and i found it perfect. I just modified two lines to avoid “Empty email” AND “Email invalid” messages.

    if($rule['name'] == $key && !in_array($rule['name'],$skipRule)) {
    $skipRule[] = $rule['name'];

    Thank you for sharing it!

    Marcelo

Leave a Reply

Using Gravatars in the comments - get your own and be recognized!

XHTML: These are some of the tags you can use: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>