CakePHP验证数组适用于许多领域

时间:2013-10-01 12:53:03

标签: php cakephp

在蛋糕模型中,我有6个字段,它们都具有相同的验证规则。有没有办法将此规则分配给所有6个字段而无需复制粘贴数组?

E.g。

public $currency_validate = array(
        'rule1'=>array(
            'rule'    => array('comparison', '>=', 0),
            'message' => 'Must be between 0 and 1'
            ),
        'rule2' => array(
            'rule'    => array('comparison', '<=', 1),
            'message' => 'Must be between 0 and 1'
            )
        );
public $validate = array(
            'usd' => $this->currency_validate,
            'gbp' => $this->currency_validate,
            'eur' => $this->currency_validate,
            //etc
        );

不起作用,因为不允许在类中动态分配属性。

1 个答案:

答案 0 :(得分:0)

您可以在 beforeValidate(array $ options = array())方法中添加规则:

public $currency_validate = array(
    'rule1'=>array(
        'rule'    => array('comparison', '>=', 0),
        'message' => 'Must be between 0 and 1'
        ),
    'rule2' => array(
        'rule'    => array('comparison', '<=', 1),
        'message' => 'Must be between 0 and 1'
        )
    );
public $validate = array(
        'usd' => array(),
        'gbp' => array(),
        'eur' => array(),
        //etc
    );

public function beforeValidate(array $options = array()) {
    $this->validate = array(
        'usd' => $this->currency_validate,
        'gbp' => $this->currency_validate,
        'eur' => $this->currency_validate,
        //etc
    );
    return true; //otherwise the current save() execution will abort 
}