Zend Framework:如何在Zend Form中添加自定义验证规则?

时间:2010-10-08 05:20:31

标签: validation email zend-framework zend-form

我创建了一个zend表单,与验证一起正常工作。

无论如何我可以在此表单中为电子邮件地址添加自定义验证,例如我想设置验证以检查用户提供的电子邮件地址是否是hotmail,因为我只想接受hotmail电子邮件地址

<?php
class Application_Form_RegistrationForm extends Zend_Form{

    public function init(){

        $firstname = $this->createElement('text', 'firstname');
        $firstname->setLabel('Firstname: ')
                ->setRequired(true);

        $lastname = $this->createElement('text', 'lastname');
        $lastname->setLabel('Lastname: ')
                ->setRequired(true);

        $email = $this->createElement('text', 'email_address');
        $email->setLabel('Email Address: ')
                ->setRequired(true);

        $register = $this->createElement('submit', 'register');
        $register->setLabel('Create new Account')
                ->setIgnore(true);

        $this->addElements(array(
            $firstname, $lastname, $email, $register
        ));




    }

}

?>

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

class Mylib_Validate_UniqueEmail extends Zend_Validate_Abstract
{
    const NOT_HOTMAIL = 'notHotmail';
    protected $_messageTemplates = array(
        self::NOT_HOTMAIL => "'%value%' is not a hotmail email address."
    );

    public function isValid($value)
    {
        $valueString = (string) $value;

        $this->_setValue($valueString);

        $email = explode('@',$value);

        if (!substr_count($email[1],'hotmail') ) {
            $this->_error(self:NOT_HOTMAIL);
            return false;
        }

        return true;
    }
}

这将是需要在表单中添加的验证类。