Validation API上的Cakephp验证消息

Validation API上的Cakephp验证消息,validation,rest,cakephp,cakephp-2.0,Validation,Rest,Cakephp,Cakephp 2.0,我有我的web客户端的注册表和相同注册表的API。我希望使用与模型中web客户端相同的规则来验证API中的数据,但需要显示不同的消息。在web客户端中,我有类似“字段名中的错误”的消息,对于API,我需要类似“1”的消息。现在,我在控制器中使用if语句执行此操作,如果错误为“字段名中的错误”,请给我消息“1”。问题是,如果我必须验证10个字段,我需要在控制器中编写10条if语句。有没有更聪明的方法 型号: class User extends AppModel { public $va

我有我的web客户端的注册表和相同注册表的API。我希望使用与模型中web客户端相同的规则来验证API中的数据,但需要显示不同的消息。在web客户端中,我有类似“字段名中的错误”的消息,对于API,我需要类似“1”的消息。现在,我在控制器中使用if语句执行此操作,如果错误为“字段名中的错误”,请给我消息“1”。问题是,如果我必须验证10个字段,我需要在控制器中编写10条if语句。有没有更聪明的方法

型号:

class User extends AppModel {

    public $validate = array(
        'name'=>array(
           'rule'=>'notEmpty',
           'message'=> ‘Error in field Name’        
        )
     );
}
控制器

  class RestUsersController extends AppController {

       $errors = $this->User->invalidFields();

       if(array_shift(array_slice($errors, 0, 1))== ' Error in field Name '){ 

            $message='1';
        }
   }

提前谢谢你

您可以在模型中的
beforeValidation()
回调中设置验证规则。在这种方法中,您可以准备两个验证集数组,并在AppModel中放入一个变量,该变量将像开关一样工作,以选择合适的验证集。您只需在
beforeFilter()
callback中为API控制器中的此开关设置正确的值即可使其正常工作。为了更好地理解我的解决方案,请查看下面的代码示例

型号

class User extends AppModel {

    public function beforeValidate($options = array()) {
        parent::beforeValidate($options);
        $this->_prepareValidationRules();
    }

    protected function _prepareValidationRules() {
        if (!empty($this->apiValidation)) { // for API
            $this->validate = array(
                'name' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Error in field Name'
            ));
        } else { // default behaviour
            $this->validate = array(
                'name' => array(
                    'rule' => 'notEmpty',
                    'message' =>  '1'
            ));
        }
    }
}
控制器

class RestUsersController extends AppController {
    public function beforeFilter() {
        parent::beforeFilter();
        $this->User->apiValidation = true;
    }
}
AppModel.php

class AppModel extends Model {

    public $apiValidation = false;

    (...)
}

当然,您可以将
$apiValidation
变量定义为受保护的,并通过方法对其进行控制,但这取决于您。

谢谢@marian0,非常适合我的情况,谢谢您的回复!