1

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

例如

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

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

4

1 回答 1

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 
}
于 2013-10-01T13:14:22.863 回答