January 23, 2010 | In: Application Security, HTML, PHP
Zend_Validate_StringEquals
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
"%field1% and %field2% are not equal.",
self::MISSING => "One or both strings are missing."
);
/**
* @var array
*/
protected $_messageVariables = 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)
{
if(!is_array($value) OR sizeof($value) < 2) {
$this->_error(self::MISSING);
}
$this->_field1 = array_shift($value);
$this->_field2 = array_shift($value);
if($this->_case === true) $function = 'strcmp';
else $function = 'strcasecmp';
if(0 !== $function($this->_field1,$this->_field2)) $this->_error(self::NOT_EQUAL);
if (count($this->_messages)) {
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.
$filters = array('password' => 'StringTrim', 'cpassword' => 'StringTrim');
$validators = array(
'Password' => array(
'presence' => 'required',
array('StringLength',5,15),
'fields' => 'password',
'messages' => "Passwords must be between 5 and 15 characters in length."),
'Confirm password' => array(
array('StringEquals'),
'fields' => array('password','cpassword'),
'messages' => array(
0 => array(
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);