开发者

How do I write a custom validator for a zend form element with customized error messages?

I have a question field with a list of allowed characters : A-Z,0-9,colon (:), question mark (?), comma(,), hyphen(-), apostrophe ('). I have the regex which works fine, in the fashion :

 $question->addValidator('regex', true, array(<regular expresstion>))

The default error message is something like ''' does not match against pattern ''

I want to write a custom error message that says ' is not allowed in this field'

Is there a simple way to do it using the existing zend components that I'm missing?

Is writing a custom validator the only way to achieve what I'm trying to 开发者_开发百科achieve? If yes, how do I write a custom validator (I looked at the documentation and didn't quite understand how I can customize the error messages) If there is any other way, I'd most appreciate that input too.

Thanks for taking the time to answer this!


Yes, the custom validator fits your needs. On how to write it, please refer to this manual.

With regards to a code snippet, here's a simple validator(partial) for validating employer ID

protected $_messageTemplates = array(
    self::UNIQUE => 'The id provided is already in use',
    );

public function isValid($value, $context = null)
{
    $this->_setValue($value);

    $personnel = new Personnel();
    $isValid = true;

    if( $personnel->isExistingIdEmployee($value) && ($value != $this->_id) ) {
        $this->_error(self::UNIQUE);
        $isValid = false;
    }

    return $isValid;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜