【问题标题】:How to validate a element based on another element's value?如何根据另一个元素的值验证一个元素?
【发布时间】:2012-01-29 05:51:16
【问题描述】:

我有一个客户 ID 和一个唯一客户哈希。当我注册这些数据时,它工作正常。 为了清楚起见,我不生成哈希。

我用来验证唯一哈希是否已经存在的代码:

protected function _getValidator($field)
{
    return array(
        'Db_NoRecordExists',
        true,
        array(
            'table' => 'anunciantes',
            'field' => $field,
            'messages' => array(
                'recordFound' => ucfirst($field) . ' "%value%" is registered'
            )
        )
    );
}

但是当我必须编辑该客户端时,我想验证该哈希是否已经存在,以及该哈希是否属于该客户端。

我是怎么做到的?我已经尝试通过使用 db 验证器的 'exclude' 选项并传递 $this->getValue('id') 来获取 id 的值,但该调用返回 null

【问题讨论】:

    标签: php oop zend-framework zend-form zend-validate


    【解决方案1】:

    要验证哈希是否已经存在并属于特定用户,您可以使用以下带有自定义排除条件的验证器。我假设哈希是一个隐藏的文本字段,其中包含来自数据库的哈希。

    protected function _getEditValidator($field, $userId, $db = null)
    {
        if ($db == null) $db = Zend_Db_Table::getDefaultAdapter();
    
        array(
            'Db_RecordExists',
            true,
            array(
                'table' => 'anunciantes',
                'field' => $field,
                'exclude' => $db->quoteInto('user_id = ?', $userId)
            )
        );
    }
    

    这将检查以确保元素中包含的散列与属于user_id 的数据库中的散列相匹配。我们正在重写 exclude 选项以使其哈希值必须与为给定用户 ID 设置的值匹配。

    查询大致如下所示:

    SELECT `users`.`db_hash_col` FROM `users` WHERE (`db_hash_col` = :value) AND (user_id = 1234) LIMIT 1
    

    在编辑用户和创建用户时,您需要使用一些逻辑来交换验证器。你可以这样设置:

    if ($editing) {
        $this->getElement('hash')
             ->setValidators(
                 array($this->_getEditValidator('db_hash_col',
                                                $this->getElement('id')->getValue());
    }
    

    另外,在您提到的问题中,您使用$this->getValue('id');我相信这实际上应该是$this->getElement('id')->getValue()

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      您必须在表单中为该字段添加一个验证器,例如..

      $name->addValidator(
          'Db_NoRecordExists', 
          true, 
          array(
              'table' => 'currencies',
              'field' => $field,
              'messages' => array( "recordFound" => "This Client Id already exists in our DB") ,
              'exclude' => array(
                   'field' => 'id',
                   'value' => $this->_attribs['id']
               )
          )
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-15
        • 1970-01-01
        • 1970-01-01
        • 2017-01-25
        相关资源
        最近更新 更多