2008年11月24日星期一

Re: [fw-mvc] Form Validation Messages

-- aSecondWill <willjbarker@gmail.com> wrote
(on Monday, 24 November 2008, 02:35 PM -0800):
> Matthew Weier O'Phinney-3 wrote:
> > I'd do this:
> >
> > $this->setRequired(true)
> > ->addValidators(array(
> > array('NotEmpty', true, array('messages' => array(
> > 'isEmpty' => 'Please enter a password.',
> > ))),
> > 'Alnum',
> > array('StringLength', false, array(4, 20)),
> > ))
> > ->addFilter('StringToLower');
> >
> > Hope that makes sense!
>
> um, only just. as in it works, but i don't really get whats happening.
>
> to add different messages for blank or invalid email addresses, i did this:
>
> $email->setRequired(true)
> ->addValidators(array(
> array('NotEmpty', true, array('messages' => array(
> 'isEmpty' => 'You must enter an email, or else.',
> ))),
> 'EmailAddress',
> array('EmailAddress', false, array('messages' => array(
> 'emailAddressInvalid' => 'An actual email address would be
> awesome.'))),

You realize you're adding the EmailAddress validator twice here, right?
The first time passes no arguments to it, while the second does.

> ))
> ;
>
> I don't know what the true / false second parameters do? i changed the
> second one to false and it dosn't change the behaviour.

The second argument is a "breakChainOnFailure" flag -- basically, if any
validators appear *after* that validator, then none of the following
validators will be executed.

> This seems a bit hard to use, so i tried doing it differently:
>
> $validator = new Zend_Validate_NotEmpty();
> $validator->setMessage('You must enter an Email address.');
> $email->addValidator($validator);
> $validator = new Zend_Validate_EmailAddress();
> $validator->setMessage('You must enter a valid Email
> address.',Zend_Validate_EmailAddress::INVALID);
> $email->addValidator($validator);
>
> which dosn't throw an error, but then dosn't trap empty or invalid emails
> either. Do i have to set a 'break chain on error' boolean, and if so, where?

When you add the validator, pass a boolean true as the second argument:

$email->addValidator($validator, true);

> Finaly, is there a better way to set the default error messages than in the
> zend framework validate clases?

The easiest way is to use translation adapters, and the easiest and most
performant of these is the array adapter. The manual details how to add
translation adapters to your form:

http://framework.zend.com/manual/en/zend.form.i18n.html

--
Matthew Weier O'Phinney
Software Architect | matthew@zend.com
Zend Framework | http://framework.zend.com/

没有评论: