Cake PHP custom validation rule

匿名 (未验证) 提交于 2019-12-03 01:41:02

问题:

I got a problem with a custom validation rule in Cake 2.X

I want to check if the entered zipcode is valid and therefore a function in the class zipcode is called from the class post.

But the validation returns false all the time.

Appmodel in class post (rule-3 is it):

'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!'             )         )     ),

Appmodel in class zipcode:

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;     }   }

回答1:

I think this:

'Zipcode.zipcode' =>$zipcode

...needs to be this:

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



回答2:

Careful what you expect inside the validation rule. Use debug() etc to find out what exactly is coming in. $data is always an array here.

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); }


回答3:

try this for only model validation.

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


回答4:

The magic to do here is to import the appmodel-class you want to use in the class you call the validation-function. That works with the following statement:

$Zipcode = ClassRegistry::init('Class to use - in my case "Zipcode"');



转载请标明出处:Cake PHP custom validation rule
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!