Cakephp validation error
控制器代码
1 2 3 4 5 | if(!empty($this->data)){ if($this->{$this->modelClass}->signupValidate()){ $this->{$this->modelClass}->save($this->data); } } |
型号代码
1 2 3 4 5 6 7 8 9 10 11 12 | function signupValidate(){ $validate1 = array( 'first_name' => array( 'rule1' => array( 'rule' => 'notEmpty', 'message' => __('Please enter first name',true) ) ) ); $this->validate = $validate1; return $this->validates(); } |
验证无法正常工作
您的模型将在保存数据之前自动调用验证,否则您可以在控制器中使用以下代码
在您的控制器中
1 2 3 4 5 | $this->loadModel('YourModel'); if($this->YourModel->validates()) { $this->YourModel->save($this->data); } |
在模型类中添加以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | var $validate = array( 'first_name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'This field cannot be left blank.' ) ), 'last_name' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'This field cannot be left blank.' ) ), 'phone' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'Phone number should be valid.' ), 'phone' => array( 'rule' => array('phone', null, 'us'), 'message' => 'Phone number should be valid e.g. 555-555-5555' ) ), 'email' => array( 'email' => array( 'rule' => 'email', 'message' => 'Please enter a valid email address' ), 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'This field cannot be left blank' ), 'validEmail' => array( 'rule' => array('validEmail'), 'message' => 'Email address does not exist.' ) ), 'captcha_code' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'This field cannot be left blank' ) ), 'address' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'This field cannot be left blank.' ) ), 'city' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'This field cannot be left blank.' ) ), 'street' => array( 'notEmpty' => array( 'rule' => 'notEmpty', 'message' => 'This field cannot be left blank.' ) ) ); |
你应该在控制器中设置
1 | $this->{$this->modelClass}->set($this->data); |
像这样
1 2 3 4 5 6 | if(!empty($this->data)){ $this->{$this->modelClass}->set($this->data); if($this->{$this->modelClass}->signupValidate()){ $this->{$this->modelClass}->save($this->data); } } |