Przy pracy nad pewnym projektem opartym o Zend Framework, zaistniała potrzeba walidacji elementów formularza, tak, by zawartość jednego elementy była identyczna jak innego, np hasło i jego potwierdzenie. Aby tego dokonać wystarczy stworzyć prosty walidator:
<?php class Validate_Confirm extends Zend_Validate_Abstract { /** * * @var Zend_Form_Element */ protected $_matchedField; const NOT_CONFIRMED = 'notConfirmed'; protected $_messageTemplates = array( self::NOT_CONFIRMED => 'notConfirmed' ); public function __construct( Zend_Form_Element $matchedField ) { $this->_matchedField = $matchedField; } public function isValid( $value ) { if( $this->_matchedField->getValue()==$value ) { return true; } else { $this->_error( self::NOT_CONFIRMED ); return false; } } } ?> |
następnie taki walidator używamy w naszym formularzu:
<?php class Activation extends Zend_Form { public function init(){ //user_name $user_name = $this->createElement('text', 'user_name'); $user_name->setRequired(true); $user_name->setLabel( 'user_name' ); $this->addElement($user_name); //user_password $user_password = $this->createElement('password', 'user_password'); $user_password->setRequired(true); $user_password->setLabel( 'user_password' ); $this->addElement($user_password); //user_password_repeat $user_password2 = $this->createElement('password', 'user_password_repeat'); $confirmVal = new Validate_Confirm( $user_password ); $user_password2->addValidator($confirmVal); $user_password2->setRequired(true); $user_password2->setLabel( 'user_password_repeat' ); $this->addElement($user_password2); //submit $submit = $this->createElement( 'submit', 'submit' ); $submit->setLabel('btnNext'); $this->addElement($submit); } } ?> |
Dzięki takiemu zabiegowi nasz formularz sam sprawdzi, czy odpowiednie pola są sobie równe.
