2012-09-05 76 views
2

我有一個字段,應該接受整數值,其與另一個字段的總和應爲100. 爲了做到這一點,我已經編寫了像這樣的自定義方法。CakePHP如何使用在自定義驗證函數中內置驗證規則?

'share' => array(
    'share' => array(
     'rule' => array('share'), 
     'message' => 'This field is required.', 
     'last' => true, 
    ), 

這裏我想用內置的驗證方法來檢查天氣這個字段是數字。

function share() { 
     if($this->data['Model']['commission_type'] == "usage_based") { 
      // if($this->data['SmeCommission']['share']) { // Want to check this is a valid integer How can I built in Numeric validation here 
       // Next validation to sum is equal to 100 with another field in the data. 
      // } 
     } else { 
      return true; 
     } 
    } 
+0

http://stackoverflow.com/questions/3672048/using-core-validation-within-的重複custom-validation-on-cakephp-forms-models – dirtyhandsphp

+0

檢查http://book.cakephp.org/complete/1143/Data-Validation#Adding-your-own-Validation-Methods-1181 4.1.5.2添加你自己的驗證方法部分最後一個例子(第3個) – dirtyhandsphp

回答

2

對該字段使用多個規則。如下所示,第一條規則檢查值是數字,然後檢查總和的自定義規則。

'share' => array(
    'numeric' => array(
     'rule' => 'numeric' 
    ), 
    'share' => array(
     'rule' => array('share'), 
    ) 
), 

如果你想直接使用驗證規則,你可以這樣做:

Validation::numeric(array('key' => 'value'));