开发者

Zend Framework: How to add a custom validation rule in Zend Form?

开发者 https://www.devze.com 2023-01-19 17:39 出处:网络
I have a created a zend form, works fine along with validations. Is there anyway I can add a custom validation within this form for the email address, for example I want to set a validation to check

I have a created a zend form, works fine along with validations.

Is there anyway I can add a custom validation within this form for the email address, for example I want to set a validation to check if the email address supplied by the user is hotmail, as I want to accept only hotmail email addresses.

<?php
class Application_Form_RegistrationForm extends Zend_Form{

    public function init(){

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

        $lastname = 开发者_如何学Go$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
        ));




    }

}

?>

Any help will be appreciated.


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;
    }
}

This will be the validate class that will be needed to be added in the form.

0

精彩评论

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