Validate Select Field in Zend Form

09.Dec.2011

When setting your Zend Form with Select field you don’t always wish to have label on that filed but rather “Select one” as a first option.

Setting the required flag on Zend Select, or adding notEmpty validator won’t always work especially if your box is being populated dynamically.

Let’s say you have something like this:

<select name="example">
    <option value="Select one">Select one</option>
    <option value="value1">value1</option>
    <option value="value2">value2</option>
    <option value="value3">value3</option>
</select>

You could easily validate this by adding Zend_Validate_Regex and passing any pattern to it
as follows in snippet:

$select->addValidator(new Zend_Validate_Regex( '/[^Selectsone]/' ))
    ->addErrorMessage('You need to select one value');

This one will check if the value is not “Select one” and let your user pass validation only in that case.