Cake PHP自定义验证规则

时间:2013-04-18 00:15:53

标签: class cakephp validation

我在Cake 2.X中遇到了自定义验证规则的问题

我想检查输入的邮政编码是否有效,因此从类邮件调用类zipcode中的函数。

但验证始终返回false。

课程中的Appmodel(规则3是它):

'DELIVERYAREA' => array(
        'rule-1' => array(
            'rule' => array('between', 5, 5),
            'message' => 'Bitte eine fünfstellige Postleitzahl eingeben'
        ),
        'rule-2' => array(
            'rule' => 'Numeric',
            'message' => 'Bitte nur Zahlen eingeben'
        ),
        'rule-3' => array(
            'exists' => array(
                'rule' => 'ZipExists',
                'message' => 'Postleitzahl existiert nicht!'
            )
        )
    ),

类zipcode中的Appmodel:

class Zipcode extends AppModel {
  var $name = 'Zipcode';

  var $validate = array(
    'zipcode' => array(
       'length' => array(
              'rule' => array('maxLength', 5),
              'message' => 'Bitte einen Text eingeben'
          ),
         'exists' => array(
          'rule' => array('ZipExists'),
          'message' => 'Postleitzahl existiert nicht!'

       )
    )         
  );

  function ZipExists($zipcode){

    $valid = $this->find('count', array('conditions'=> array('Zipcode.zipcode' =>$zipcode)));
    if ($valid >= 1){
      return true;
    }
    else{
      return false;
    }
  }

我希望这简直容易吗? 提前致谢

4 个答案:

答案 0 :(得分:0)

我想这个:

'Zipcode.zipcode' =>$zipcode

......需要这样:

'Zipcode.zipcode' =>$zipcode['zipcode']

答案 1 :(得分:0)

在验证规则中仔细考虑您的期望。使用debug()等来找出确切的内容。$ data始终是一个数组。

public function zipExists($data) {
    $zipcode = array_shift($data); // use the value of the key/value pair
    $code = $this->find('first', array('conditions'=> array('Zipcode.zipcode' =>$zipcode)));
    return !empty($code);
}

答案 2 :(得分:0)

尝试仅用于模型验证。

  function ZipExists(){

    $valid = $this->find('count', array('conditions'=> array('Zipcode.zipcode' =>$this->data['Zipcode']['zipcode'])));
    if ($valid >= 1){
      return true;
    }
    else{
      return false;
    }

答案 3 :(得分:0)

我找到了解决方案。 Cake希望自定义验证规则位于调用规则的特定类中。因此,当您在课程帖子中调用自定义规则时,必须在课程帖子中写下自定义函数,否则蛋糕将无法找到它并且每次都将其验证为假。

这里要做的魔术是导入要在调用验证函数的类中使用的appmodel-class。这适用于以下声明:

$ Zipcode = ClassRegistry :: init('要使用的类 - 在我的情况下是“Zipcode”');

但是如果你的表与hasAny或belongsTo和stuff相互关联,那么自定义函数可以不用它。您不能错过的另一个重点是,所有验证功能都必须通过“public function xyz”引入,否则蛋糕也不会找到它们。

相关问题