我想在 where 子句中添加对多个值的检查。Db_RecordExists 只检查一个文件。我已经读到您可以扩展 zend validate 抽象类,并且您可以拥有自己的验证器。请给我一个关于这个的小例子。
谢谢...
我想在 where 子句中添加对多个值的检查。Db_RecordExists 只检查一个文件。我已经读到您可以扩展 zend validate 抽象类,并且您可以拥有自己的验证器。请给我一个关于这个的小例子。
谢谢...
你到底想做什么?对我来说,您甚至不需要自定义验证器。
如果您仔细阅读源代码,Zend_Validate_Db_Abstract
您会注意到构造函数上方的这个 phpDoc:
提供与 Zend_Validate_Db Validators 一起使用的基本配置 设置 $exclude 允许从匹配中排除单个记录。Exclude 可以是包含 where 子句的字符串,也可以是带有
field
和value
键的数组,用于定义添加到 sql 的 where 子句。可以选择提供数据库适配器以避免使用已注册的默认适配器。支持以下选项键:
- 'table' => 要验证的数据库表
- 'schema' => 模式键
- 'field' => 检查匹配的字段
- 'exclude' => 要从查询中排除的可选 where 子句或字段/值对
- 'adapter' => 要使用的可选数据库适配器
这意味着如果您想使用多个值检查记录是否存在,您可以简单地将 where 子句传递给验证器,而不是一对字段/值:
$where = 'user_id != 110 AND email != "email@example.com"';
$where = array('users', 'email', $where);
$element->addValidator('db_NoRecordExists', true, $where)
这将基本上检查用户表中是否存在记录,并排除 用户 id != 110或email@example.com的行。当然,我建议您使用Zend_Db 方法,例如quoteIdentifier()
为了生成完全转义的查询表达式。
当然,您可以根据需要添加任意数量的字段。
您通常需要做的就是重写 isValid() 方法来制作自定义验证器,
这是自定义验证器的示例:
<?php
class My_Validator_Usphone extends Zend_Validate_Abstract {
const PHONE = 'phone';
protected $_messageTemplates = array(
self::PHONE => "'%value%' is not a valid U.S. phone number.
Phone number must be entered in (xxx)xxx-xxxx or xxx-xxx-xxxx format."
);
public function isValid($value) {
$this->_setValue($value);
$isValid = TRUE;
$pattern = ('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/');
if (!preg_match($pattern, $value)) {
$this->_error(self::PHONE);
$isValid = FALSE;
}
return $isValid;
}
}
Db_RecordExists 非常简单,但它可以扩展Zend_Validate_Db_Abstract
并且应该很容易修改以针对两个字段进行验证,但是您可能必须覆盖isValid()
和getSelect()
/或_query()
接受多个值。
class Zend_Validate_Db_RecordExists extends Zend_Validate_Db_Abstract
{
public function isValid($value)
{
$valid = true;
$this->_setValue($value);
$result = $this->_query($value);
if (!$result) {
$valid = false;
$this->_error(self::ERROR_NO_RECORD_FOUND);
}
return $valid;
}
}