我在Cake 2.X中遇到一个自定义验证规则的问题
我想检查输入的zipcode是否有效,因此类zipcode中的函数是从类post调用的。
但是验证总是返回false。
类post中的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;
}
}我希望它是愚蠢的简单的东西?提前感谢
发布于 2013-04-20 16:20:29
我找到了解决方案。Cake希望自定义验证规则位于调用规则的特定类中。所以,当你在post类中调用自定义规则时,自定义函数必须写在post类中,否则蛋糕不会找到它并每次都验证它为false。
这里要做的魔术是导入您想要在调用验证函数的类中使用的appmodel-class。这与以下语句一起使用:
$Zipcode =ClassRegistry::init(‘要使用的类-在我的例子中是"Zipcode"');
但是,如果您的表与hasAny或belongsTo等关联,则自定义函数将在没有它们的情况下工作。另一个你不能错过的要点是,所有的验证函数都必须用"public function xyz“来引入,否则蛋糕也找不到它们。
发布于 2013-04-18 14:07:44
我认为:
'Zipcode.zipcode' =>$zipcode
...needs是这样的:
'Zipcode.zipcode' =>$zipcode['zipcode']
发布于 2013-04-18 16:07:52
注意验证规则中的预期内容。使用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);
}https://stackoverflow.com/questions/16072455
复制相似问题