views:

1925

answers:

4

I'm seeking some examples of how people implement validation logic in the Zend Framework.

My ideal implementation would keep the validation outside the controller and allow validating "Confirm password" fields and file uploads.

+4  A: 

Are you using Zend_Form for your forms? I tend to apply validators within the form for each Zend_Form_Element. This is how I do it:

class Form_Login extends Zend_Form
{
    public function init() {
        $this->setMethod('post');

        $validator = new Zend_Validate_Regex('([A-Za-z0-9]+)');
        $validator->setMessage(
        'Your username can only contain letters, numbers and underscores (_).');

        $username = new Zend_Form_Element_Text('username');
        $username->setLabel('Your Username');
        $username->setDescription('The username you use to login');
        $username->setAllowEmpty(false);
        $username->setRequired(true);
        $username->addValidator($validator);

        $submit = new Zend_Form_Submit('login');
        $submit->setLabel('Login');

        $this->addElements(array($username, $submit));
    }
}

(Customising error messages)

And then in your controller:

// $form is an instance of the extended Zend_Form
if (!$form->isValid()) {
    $validator->getMessages()
    // flashMessenger helpers or just simple view appends
}

My ideal implementation would keep the validation outside the controller and allow validating "Confirm password" fields and file uploads.

I've seen mention of confirm password validators in the reference guide (but can't find them now, typical) but it should be easy to find one on Google.

File uploads will definitely require you to write a custom validator.

Ross
A: 

Yes, this is the recommended way to do data validation. Thanks! I would like to see more examples.

I'm sort of a control freak when it comes to HTML, so I try to stay away from Zend_Form. I know it can be heavily customized, but I remember hitting a roadblock at some point, so I decided to stick with plain html forms.

Adrian Grigore
I had a little trouble with the decorators side of Zend_Form (and still do) but I've just learned to beat that by styling dl/dd/dt's correctly :)
Ross
I had this same issue until I found this: http://www.zendframework.com/manual/en/zend.form.standardDecorators.html#zend.form.standardDecorators.viewScriptWrite your form display in HTML instead of letting Decorators do the work for you.
Rob Booth
A: 

Perhaps you should have a look at: http://weierophinney.net/matthew/archives/200-Using-Zend_Form-in-Your-Models.html. Matthew Weier O'Phinney (one of the Zend Fraework core developers) shows an approach that needs getting used to - but it's worth a look.

Stefan Gehrig
A: 

Specifically for a "confirm password" type of validation, check out The Zym Framework (a Zend Framework extension). It has a built in validator for this exact purpose. Try out the Zym_Validate_Confirm class.

leek