views:

185

answers:

1

Is there a way to get a validator to fire even if the form element isn't required?

I have a form where I want to validate the contents of a texbox (make sure not empty) if the value of another form element, which is a couple of radio buttons, has a specific value selected. Right now I'm doing this by overriding the isValid() function of my form class and it works great. However, I'd like to move this to either its on validator or use the Callback validator. Here's what I have so far, but it never seems to get called unless I change the field to setRequired(true) which I don't want to do at all times, only if the value of the other form element is set to a specific value.

// In my form class's 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;
    }
}
A: 

Looks like if you use setAllowEmpty(false) in place of setRequired(false) then you validator will still get called. So I now have:

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

and it is working great!

Jeremy Hicks