ba0708
ba0708

Reputation: 10599

Validate default values

I have a form which consists of selects/dropdowns. I have set their default values to be -1. When the form is submitted, I want to validate that the submitted value is not equal to the default value. I tried setRequired(true), but as far as I know, that is just a convenient way of adding a notEmpty validator, which is not really what I want.

Here is a part of my form:

    $select = new Zend_Form_Element_Select('myselect');
    $select->setMultiOptions(array(
                        '-1' => 'Gender',
                        '0' => 'Female',
                        '1' => 'Male'
                    ))
                    ->addValidator(new Zend_Validate_Int(), false);

    $this->setDefaults(array('myselect' => -1));

And here is my controller:

if ($this->getRequest()->isPost()) {
            $form = new My_Form_Contact();

            if ($form->isValidPartial(array('myselect' => $this->getRequest()->getPost('myselect')))) {
                // "myselect" is valid
            }

I need to use the isValidPartial method because I need to use different logic depending on which elements have a value that is different from their default value. I guess what I need is a notEqual validator, but I couldn't find one. I know that it is possible to make my own validators, but I wanted to ask if there is an easier way first. I also looked at Zend_Validate_Identical, but I don't think I can make use of it in this case.

To sum up: I only want my select to be validated successfully if the submitted value is not equal to the default value.

Upvotes: 0

Views: 631

Answers (1)

Ross Smith II
Ross Smith II

Reputation: 12179

The simplest solution is to use an empty string as the default:

$select->setMultiOptions(array(
                    '' => 'Gender',
                    '0' => 'Female',
                    '1' => 'Male'
                ))
                ->addValidator(new Zend_Validate_Int(), false)
                ->addValidator(new Zend_Validate_NotEmpty(), false);

$this->setDefaults(array('myselect' => ''));

but I'm guessing you already thought of that, and discounted it from some reason.

So, the next easiest is to use GreaterThan():

$select->setMultiOptions(array(
                    '-1' => 'Gender',
                    '0' => 'Female',
                    '1' => 'Male'
                ))
                ->addValidator(new Zend_Validate_Int(), false)
                ->addValidator(new Zend_Validate_GreaterThan(-1), false);

$this->setDefaults(array('myselect' => '-1'));

I hope that is what you are looking for.

Upvotes: 1

Related Questions