Posts Tagged Zend_Validate
Zend_Validate_StringEquals
Posted by jervin in Application Security, HTML, PHP on January 23, 2010
If you ever wonder where that 'StringEquals' validator rule taken as example from the Zend_Filter_Input documentation page results in an error like below, well read again. It was clearly stated as 'hypothetical'.
Plugin by name 'StringEquals' was not found in the registry; used paths: Zend_Validate_: Zend/Validate/
Given such validator would be useful on a number of situations i.e. confirming passwords, emails, etc. I present to you my own version of the class.
<?php class Zend_Validate_StringEquals extends Zend_Validate_Abstract { const NOT_EQUAL = 'stringNotEqual'; const MISSING = 'stringMissing'; /** * @var array */ self::NOT_EQUAL => "%field1% and %field2% are not equal.", self::MISSING => "One or both strings are missing." ); /** * @var array */ 'field1' => '_field1', 'field2' => '_field2' ); protected $_case = false; protected $_field1 = null; protected $_field2 = null; /** * Sets validator options * * @param boolean $case * @return void */ public function __construct($case = false) { $this->_case = $case; } /** * Defined by Zend_Validate_Interface * * Returns true if and only if the the 2 strings are equal * * @param array $value * @return boolean */ public function isValid($value) { $this->_error(self::MISSING); } if($this->_case === true) $function = 'strcmp'; else $function = 'strcasecmp'; if(0 !== $function($this->_field1,$this->_field2)) $this->_error(self::NOT_EQUAL); return false; } else { return true; } } }
Here is a sample test case. Validate password and confirm password elements represented by 'password' and 'cpassword' element names respectively.
'presence' => 'required', 'fields' => 'password', 'messages' => "Passwords must be between 5 and 15 characters in length."), Zend_Validate_StringEquals::NOT_EQUAL => "Passwords does not match.", Zend_Validate_StringEquals::MISSING => "Both password fields must be filled.")))); $inputdata = new Zend_Filter_Input($filter,$validators,$_POST,$options);