cakephp文件字​​段验证 [英] cakephp file field validation

查看:145
本文介绍了cakephp文件字​​段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图验证cakephp模型中的文件字段有有效的扩展在创建和更新尝试验证文件只有当字段不为空。创建验证工作正常,但在更新它验证if字段是空的。我想只在字段不为空时验证扩展
这里是我在模型验证数组中的验证规则

i m trying to validate file field in cakephp in model with valid extension on create and on update try to validate file only if field is not empty.On Create the validation works fine, But on update it validates the if field is empty.I want to validate extensions only when the field is not empty here is my validation rule in model validation array

'image' => array(
        'rule1'=>array(
            'rule' => array('extension',array('jpeg','jpg','png','gif')),
            'required' => 'create',
            'allowEmpty' => true,
            'message' => 'Select Valid Image',
            'on' => 'create',
            'last'=>true
        ),
        'rule2'=>array(
            'rule' => array('extension',array('jpeg','jpg','png','gif')),
            //'required' => 'create',
            'allowEmpty' => true,
            'message' => 'Select Valid Image',
            'on' => 'update',
        ),
    ),


推荐答案

这里是正确的方法来验证图像字段与创建时所需的, image字段

Here is the correct way to validate image field with required on create and can allow empty on update of image field

图片字段验证数组

'image' => array(
    'rule1'=>array(
        'rule' => array('extension',array('jpeg','jpg','png','gif')),
        'required' => 'create',
        'allowEmpty' => true,
        'message' => 'Select Valid Image',
        'on' => 'create',
        'last'=>true
    ),
    'rule2'=>array(
        'rule' => array('extension',array('jpeg','jpg','png','gif')),
        'message' => 'Select Valid Image',
        'on' => 'update',
    ),
),

on更新操作中的beforevalidation

function beforeValidate($options = array()){
    if(empty($this->data[$this->alias]['id']))
    {
        return true;
    }
    else
    {
        if(empty($this->data[$this->alias]["image"]["name"])){
        unset($this->data[$this->alias]["image"]);
        }
        return true; //this is required, otherwise validation will always fail
    }
}

这篇关于cakephp文件字​​段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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