Zend: Use of validator from within a controller

What I have here works great except I can only retrieve a boolean response and not the error message. This exact validator sends the errors to a form when repopulated somehow. How can I access these errors from within the controller?

Controller:


$loader = new Zend_Loader_PluginLoader();
$loader->addPrefixPath('My_Validate', 'My/Validate/');
$loader->load('Username');
$validUser = new My_Validate_Username();
$result = $validUser->isValid($user); //boolean response, works fine

Validator:


class My_Validate_Username extends Zend_Validate_Abstract {

    const MSG_TAKEN = 'msgTaken';
    const MSG_MINIMUM = 'msgMinimum';
    const MSG_MAXIMUM = 'msgMaximum';
    public $minimum = 4;
    public $maximum = 32;

    protected $_messageVariables = array(
        'min' => 'minimum',
        'max' => 'maximum'
    );

    protected $_messageTemplates = array(
        self::MSG_TAKEN => "'%value%' is already taken.",
        self::MSG_MINIMUM => "'%value%' must be at least %min% characters long.",
        self::MSG_MAXIMUM => "'%value%' must be no more than %max% characters long."
    );

    public function isValid($value) {
        $this->_setValue($value);
        
        $query = new Application_Model_DbTable_Users();
        $result = $query->getUser($value);
        if(count($result) > 0) {
            $this->_error(self::MSG_TAKEN);
            return false;
        }

        if (strlen($value) < $this->minimum) {
            $this->_error(self::MSG_MINIMUM);
            return false;
        }
    
        if (strlen($value) > $this->maximum) {
            $this->_error(self::MSG_MAXIMUM);
            return false;
        }
    
        return true;
    }
}

You are returning “true” or “false” in your validator instead of an actual variable.

Try…

return $this->_error(self::MSG_MINIMUM);

instead of “return false;”

same for “return true;”… use an actual variable.

This is part of the Zend Framework. That validator is set up exactly how it has to be to return a boolean response AS WELL AS the error message to a form, and it DOES work. I’d like to not make another function with the exact some code if I don’t have to.

I understand but if your validator is only returning boolean variables then how do you expect to get a string out of it?

Your only other option would be to create another variable inside the validator and call it seperately.

For example…

if (strlen($value) < $this->minimum){
$this->_error(self::MSG_MINIMUM);
$newvariable = $this->_error(self::MSG_MINIMUM);
return false;
}

Then use $newvariable wherever you need it.

$this->_error has to be sent somewhere for the form to recover it. No chance it can be recovered from the controller?