Zend Framework Form Element Validator - check a field, even if it is not required

Is there a way to make the validator work even if the form element is not required?

I have a form where I want to check the contents of texbox (make sure it is not empty) if the value of another form element, which is a pair of radio buttons, has a specific value. Right now I am doing this by overriding the isValid () function of my form class and it works fine. However, I would like to move this to my validator or use the callback validator. Here is what I have so far, but it never calls if I have not changed the field to setRequired (true), which I do not want to do always, only if the value of another form element is set to a specific value.

// In my form class init function
$budget = new Zend_Form_Element_Radio('budget');
$budget->setLabel('Budget')
    ->setRequired(true)
    ->setMultiOptions($options);

$budgetAmount = new Zend_Form_Element_Text('budget_amount');
$budgetAmount->setLabel('Budget Amount')
 ->setRequired(false)
 ->addFilter('StringTrim')
 ->addValidator(new App_Validate_BudgetAmount());

//Here is my custom validator (incomplete) but just testing to see if it even gets called.
class App_Validate_BudgetAmount extends Zend_Validate_Abstract
{
    const STRING_EMPTY = 'stringEmpty';

    protected $_messageTemplates = array(
        self::STRING_EMPTY => 'please provide a budget amount'
    );

    public function isValid($value)
    {
        echo 'validating...';
        var_dump($value);
        return true;
    }
}
+3
1

, setAllowEmpty (false) setRequired (false), . , :

$budgetAmount->setLabel('Budget Amount')
    ->setAllowEmpty(false)
    ->addFilter('StringTrim')
    ->addValidator(new App_Validate_BudgetAmount());

+3

Source: https://habr.com/ru/post/1749260/


All Articles