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

查看:30
本文介绍了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',
        ),
    ),

推荐答案

这是在创建时使用 required 验证图像字段的正确方法,并且可以在更新图像字段时允许为空

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',
    ),
),

并在更新操作中的 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天全站免登陆