Zend_Form -> Nicely change setRequired() validate

2019-03-08 19:45发布

Say I create a text element like this:

$firstName = new Zend_Form_Element_Text('firstName');
$firstName->setRequired(true);

Whats the best way to change the default error message from:

Value is empty, but a non-empty value is required

to a custom message? I read somewhere that to replace the message, just use addValidator(..., instead (NO setRequired), like this:

$firstName = new Zend_Form_Element_Text('firstName');
$firstName->addValidator('NotEmpty', false, array('messages'=>'Cannot be empty'));

but in my testing, this doesn't work - it doesn't validate at all - it will pass with an empty text field. Using both (addValidator('NotEmp.. + setRequired(true)) at the same time doesn't work either - it double validates, giving two error messages.

Any ideas?

Thanks!

10条回答
太酷不给撩
2楼-- · 2019-03-08 20:09

An easier way to set this "site-wide" would be to possibly do the following in a bootstrap or maybe a base zend_controller:

<?php    
$translateValidators = array(
                        Zend_Validate_NotEmpty::IS_EMPTY => 'Value must be entered',
                        Zend_Validate_Regex::NOT_MATCH => 'Invalid value entered',
                        Zend_Validate_StringLength::TOO_SHORT => 'Value cannot be less than %min% characters',
                        Zend_Validate_StringLength::TOO_LONG => 'Value cannot be longer than %max% characters',
                        Zend_Validate_EmailAddress::INVALID => 'Invalid e-mail address'
                    );
    $translator = new Zend_Translate('array', $translateValidators);
    Zend_Validate_Abstract::setDefaultTranslator($translator);
?>
查看更多
3楼-- · 2019-03-08 20:12

Try the following.

$subjectElement->setRequired(true)->addErrorMessage('Please enter a subject for your message');

This worked form me.

查看更多
beautiful°
4楼-- · 2019-03-08 20:12

if you put:

$element->setRequired(false);

the validations don't work at all, you have to define:

$element->setAllowEmpty(false);

in order to get the correct behavior of the validations.

查看更多
女痞
5楼-- · 2019-03-08 20:13

One small issue. This code:

$zipCode->setLabel('Postal Code')
        ->addValidator('StringLength', true, array( 5, 5 ) )
        ->addErrorMessage('More than 5')
        ->addValidator('Digits', true)
        ->addErrorMessage('Not a digit');

Will generate both error messages if either validation fails. Isn't is supposed to stop after the first fails?

查看更多
登录 后发表回答