I've started to use Zend Framework in one of my web project. And here is existst Validator. I've noticed that ZF doesn't have that basic validator as exists.
This validator check if value existst in database. Two parametrs have to be given in constructor:
- tableName - name of model class in which validator check value
- fieldName - field name to compare in specified table
Validator use model class insted of database table name.
/**
* @author: teodor
* @date: 2008-07-04
* @description: PHP Class
*/
class Debra_Validate_Exists extends Zend_Validate_Abstract {
const MSG_EXISTS = "msg_exists";
protected $_messageTemplates = array(
self::MSG_EXISTS => "'%value%' already exists"
);
public $tableName;
public $fieldName;
/**
* Create Exists Validator. Check if spec value exists in database
*
* @param string $tableName
* @param string $fieldName
*/
public function __construct($tableName,$fieldName) {
$this->tableName = $tableName;
$this->fieldName = $fieldName;
}
/**
* Check if $value is valid
*
* @param unknown_type $value
* @return unknown
*/
public function isValid($value) {
$this->_setValue($value);
$tableName = new $this->tableName;
$select = $tableName->select()->where($this->fieldName . ' = ?',$value);
$rows = $tableName->fetchRow($select);
if(!empty($rows)) {
$this->_error();
return false;
}
return true;
}
}
No comments:
Post a Comment