cakephp验证从模型和控制器 [英] cakephp validation from both model and controller

查看:101
本文介绍了cakephp验证从模型和控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在模型中验证。此外,我已经在控制器中验证验证验证码。之后,应用程序不显示模型验证错误。如果我评论控制器代码,模型验证工作正常,并显示错误。两者都不工作。



模型代码(示例)

 用户扩展AppModel {

var $ name ='User';

var $ validate = array(
'username'=>'notempty',
'firstname'=>'notempty'
);

}



>

  if(!empty($ this-> data)){

$ this-& > set($ this-> data);
$ this-> User-> create();
$ captcha = $ this-> Session-> read('CAPTCHA_CODE');

if(strtolower($ captcha)!= strtolower($ this-> data ['User'] ['captcha']))
{
$ this-> ; User-> invalidate('captcha',__('Sorry,your entry did not match',true));
}

if($ this-> User-> save($ this-> data,array('validate'=>'only')))
{
if($ this-> User-> save($ this-> data,array('validate'=>'false'))){
$ this-& Session-> setFlash(__('Registered successfully',true));
$ this-> redirect('success');
}
} else {
$ this-> Session-> setFlash(__('Please,try again。',true));
}

}



我已经替换了 if($ this-> User-> save($ this-> data,array('validate'=>'only'))) 如果($ this-> User-> validates()),那么它也不起作用。


$ b b

请帮助

解决方案

您的代码应使用 if($ this-> User - > validates())。您遇到的不正确的行为是因为 Model :: save()重置 Model :: validationErrors ,清除您的自定义验证错误。 Model :: validates()不会,因此您的双重验证设置应该工作。



  

class User extends AppModel
{
var $ validate = array(
'my_other_field'=> array(
'rule'=>'notEmpty',
' message'=>'此字段不应为空。'

);
}

控制器:

  class UsersController extends AppModel 
{
function add()
{
if(!empty($ this-> data)){
$ this-> User-> set($ this-> data);

if('foo'!= $ this-> data ['User'] ['my_field']){
$ this-> User-> invalidate('my_field ','should be'foo。);
}

if($ this-> User-> validates()){
$ this-> flash('Form validated correctly correctly。出口;
}
}
}
}

查看:

 <?php echo $ form-> create('User',array('action'=>加')); ?> 
<?php echo $ form-> input('User.my_field',array('value'=>'bar')); ?>
<?php echo $ form-> input('User.my_other_field',array('value'=>'')); ?>
<?php echo $ form-> end('Submit'); ?>

按上述提交,表单验证错误显示在两个字段的下方,一个由控制器的验证逻辑提供,另一个来自模型的验证规则。



当然,更大的问题是通过控制器处理一些数据验证来淹没MVC角色。您可能想考虑这样:



控制器:

  class UsersController extends AppController 
{
function add()
{
if(!empty($ this-> data)){

$ captcha = $ this-> Session-> read('CAPTCHA_CODE');
$ this-> User-> setCaptchaCheck($ captcha);

if($ this-> User-> save($ this-> data,array('validate'=> true))){
$ this-& Session-> setFlash('Success');
$ this-> redirect('success',303,true);
}
}
}
}

模型:

  class User extends AppModel 
{
var $ captchaCheck ='';

var $ validates = array(
'captcha'=> array(
'matchesCheck'=> array(
'rule'=> array 'matchesCaptchaCheck','captchaCheck'),//数组的第二个值应该匹配类成员名
'message'=>CAPTCHAs不匹配


);

function matchesCaptchaCheck($ data,$ checkVar)
{
$ data = reset(array_values($ data)); //我现在不需要知道字段名称。

return low($ data)== low($ this-> {$ checkVar});
}

函数setCaptchaCheck($ captcha)
{
$ this-> captchaCheck = $ captcha;
}
}

现在,您的控制器完全不了解模型验证其数据,甚至数据如何结构化;



希望这会有帮助。


I have given validation in model. Also, I have given some validation in controller for checking the captcha code. After that, the application is not displaying the model validation errors. If I comment the controller code, model validation is working fine and displaying the errors. Both not working..

Model code (sample)

class User extends AppModel {

var $name = 'User';

var $validate = array(
    'username' => 'notempty',
    'firstname' => 'notempty'
    );

}

Controller code

if (!empty($this->data)) {

$this->User->set($this->data);
$this->User->create();
$captcha = $this->Session->read('CAPTCHA_CODE');

if (strtolower($captcha) != strtolower($this->data['User']['captcha']))
{
    $this->User->invalidate('captcha', __('Sorry, your entry did not match', true));
}

if ($this->User->save($this->data, array('validate' => 'only')))
{
    if ($this->User->save($this->data, array('validate' => 'false'))) {
        $this->Session->setFlash(__('Registered successfully', true));
        $this->redirect('success');
    }
}else {
    $this->Session->setFlash(__('Please, try again.', true));
}

}

I have replaced the if ($this->User->save($this->data, array('validate' => 'only'))) line with if ($this->User->validates()), then also it is not working.

please help

解决方案

Your code should work with if ( $this->User->validates() ). The incorrect behaviour you're having trouble with is because Model::save() resets the Model::validationErrors member, obliterating your custom validation error. Model::validates() doesn't, so your dual-validation setup should work.

For example, the following functions correctly, under CakePHP 1.2.

Model:

class User extends AppModel
{
    var $validate = array(
        'my_other_field' => array(
            'rule' => 'notEmpty',
            'message' => 'This field should not be empty.'
        )
    );
}

Controller:

class UsersController extends AppModel
{
    function add()
    {
        if (! empty($this->data)) {
            $this->User->set( $this->data );

            if ( 'foo' != $this->data['User']['my_field'] ) {
                $this->User->invalidate( 'my_field', 'Should be "foo".' );
            }

            if ( $this->User->validates() ) {
                $this->flash('Form validated correctly.'); exit;
            }
        }
    }
}

View:

<?php echo $form->create('User', array('action'=>'add')); ?> 
<?php echo $form->input('User.my_field', array('value'=>'bar')); ?> 
<?php echo $form->input('User.my_other_field', array('value'=>'')); ?> 
<?php echo $form->end('Submit'); ?> 

Submitted as-is above, form validation errors appear below both fields, one provided from the controller's validation logic, the other from the model's validation rules.

The larger issue, of course, is muddying the MVC roles by having the controller handling some data validation. You might want to consider something like this:

Controller:

class UsersController extends AppController
{
    function add()
    {
        if (! empty($this->data)) {

            $captcha = $this->Session->read('CAPTCHA_CODE');
            $this->User->setCaptchaCheck( $captcha );

            if ( $this->User->save( $this->data, array('validate'=>true))) {
                $this->Session->setFlash('Success');
                $this->redirect('success',303,true);
            }
        }
    }
}

Model:

class User extends AppModel
{
    var $captchaCheck = '';

    var $validates = array(
        'captcha' => array(
            'matchesCheck' => array(
                'rule' => array( 'matchesCaptchaCheck', 'captchaCheck' ), // second value of array should match class member-name above
                'message' => "CAPTCHAs don't match."
            )
        )
    );

    function matchesCaptchaCheck( $data, $checkVar )
    {
        $data = reset(array_values($data)); // I don't need to know the field name now.

        return low($data) == low($this->{$checkVar});
    }

    function setCaptchaCheck( $captcha )
    {
        $this->captchaCheck = $captcha;
    }
}

Now your controller is blissfully ignorant of how your model validates its data, and even of how the data is structured; and your form validation all occurs in the model.

Hope this helps.

这篇关于cakephp验证从模型和控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆