codeIgniter验证表单,Validation用法,规则设置

直接上完整代码,这个是最清楚的,数组设置验证规则。

    /**
     * 添加车辆信息
     * @desc 增加车辆信息
     * @param car_type_id int Y N 车型id,从第三方库获取
     * @param car_no_type int Y N 车牌号码类型,粤A粤B等
     * @param car_no string Y N 车牌号码
     * @param frame_no string Y N 车架号码后6位
     * @param engine_no string Y N 发动机号后6位
     * @param remark string Y N 车辆备注
     * @return int code 操作码,200表示添加成功
     * @return int code 错误操作码,3008表示添加失败
     * @return int code 错误操作码,5000表示验证出错
     * @return string msg 返回信息
     */
    public function addCar() {
        $data = array(
            'car_type_id' => $this->input->post('car_type_id'),
            'car_no_type' => $this->input->post('car_no_type'),
            'car_no' => $this->input->post('car_no'),
            'frame_no' => $this->input->post('frame_no'),
            'engine_no' => $this->input->post('engine_no'),
            'remark' => $this->input->post('remark'),
        );
        $config = array(
            array(
                'field' => 'car_no',
                'label' => '车牌号码',
                'rules' => 'trim|required|min_length[5]',
            ),
            array(
                'field' => 'frame_no',
                'label' => '车架号码',
                'rules' => 'trim|required|exact_length[6]',
            ),
            array(
                'field' => 'engine_no',
                'label' => '发动机号码',
                'rules' => 'trim|required|exact_length[6]',
                'errors' => array(
                    'required' => '这里可以输出你想显示的required错误信息',
                    'exact_length' => '这里可以输出你想显示exact_length的错误信息',
                ),
            ),
        );
        // 以下是测试信息,生产环境注释掉
        // $data = ['car_no' => 'yueudshfjdjs', 'frame_no' => '1037547965@qq.com', 'engine_no' => '13011111234'];
        // 以下为表单验证
        $this->load->library('form_validation');
        // $this->form_validation->set_data($data);
        $this->form_validation->set_rules($config);

        //如果你这个验证规则经常用,你就可以把$config数组配置文件里面,是个二维数组,如果有error信息,那就是三维数组,//验证规则在这里:application\config\form_validation.php
        //if ($this->form_validation->run('register') == false) {

        if ($this->form_validation->run() == false) {
            $this->outPutJson(5000, array(), join($this->form_validation->error_array()));
        }
        //验证通过之后进行插入数据库
        $insertId = $this->CarManageModel->my_insert('car_info', $data, TRUE);
        if (!empty($insertId)) {
            $this->outPutJson(200, $data);
        }
        $this->outPutJson(3008);
    }

//改造的insert方法,写在自己定义的基类里面,基类继承框架model类

    final public function my_insert($table = '', $data, $returnInsertId = TRUE)
    {
        if(empty($table))
        {
            $table = $this->table;
        }
        $this->db->insert($table, $data);
        if($returnInsertId)
        {
            return $this->db->insert_id();
        }
    }


//自己写的方法,写在自己定义的基类里面,基类继承框架Controller类
    /**
     * 输出json
     * @param number $code
     * @param array $data
     */
    public function outPutJson($code = 0, array $data = array(), $msg = '')
    {
        $data = is_array($data) ? $data : array();
        $this->_formatoutPutData($data);

        header('Content-Type:application/json; charset=utf-8');
        header('Cache-Control: no-cache, must-revalidate');
        header("Access-Control-Allow-Origin: {$this->config->item('allow_header')}"); // 允许任何访问(包括ajax跨域)
        header('Access-Control-Allow-Credentials: true');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        $msg = isset($this->_codeList[$code]) ? $this->_codeList[$code] : $msg;

        exit(json_encode(array(
            'data' => $data,
            'code' => intval($code),
            'msg'  => $msg,
        )));
    }

    /**
     * 格式化数组字段
     * @param array $data
     */
    private function _formatoutPutData(array &$data)
    {
        if(is_array($data) && !empty($data)){
            foreach ($data as $k => &$v){
                if(!is_array($v)){
                    $v = trim($v);
                }else{
                    $this->_formatoutPutData($v);
                }
            }
        }
    }

完整Controller类如下:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
    protected $_codeList = array(); // 接口code列表
    protected $_apiCodeList = array(); // 业务接口code
    protected $_debug = FALSE;

    public $userToken = NULL;
    public $userSecret = NULL;
    public $adminUserId = 0;
    public $isSuperAdmin = FALSE;
    public $roleId = 0;

    const TEXT_NO_CONTENT = '请填写内容';

    public function __construct()
    {
        parent::__construct();
        $this->load->config('siteinfo');
        // $this->load->library('OptLogLib'); TODO 日志记录
        $this->load->library('Session');
        $this->load->helpers('cookie');
        $this->load->config('code_list');
        $this->load->config('pass_access');
        $this->_codeList = $this->config->item('code_list');
        $this->_codeList = $this->_codeList + $this->_apiCodeList; // 合并接口code
        $this->_debug = $this->input->post_get('__debug__');

        $this->userToken = get_cookie('user_token');
        $this->userSecret = get_cookie('user_secret');

        $passAccess = $this->config->item('pass_access');
        foreach($passAccess as $key => $v)
        {
            $passAccess[$key] = strtolower($v);
        }
        $urlAction = strtolower($this->router->class . '/' . $this->router->method);

        $this->adminUserId = $this->_getUserIdByToken();
        $this->isSuperAdmin = $this->_isSuper($this->adminUserId);
        $this->roleId = $this->_getUserInfo('role_id');
        if(!in_array($urlAction, $passAccess) && !getenv('LOGIN_DEBUG')) //
        {
            if(!$this->_isLogined())
            {
                $this->outPutJson(409);
            }

            /* 验证用户权限
            if(!$this->_checkAccess($this->adminUserId))
            {
                $this->_outPutJson(301);
            } */
        }
    }

    /**
     * 输出json
     * @param number $code
     * @param array $data
     */
    public function outPutJson($code = 0, array $data = array(), $msg = '')
    {
        $data = is_array($data) ? $data : array();
        $this->_formatoutPutData($data);

        header('Content-Type:application/json; charset=utf-8');
        header('Cache-Control: no-cache, must-revalidate');
        header("Access-Control-Allow-Origin: {$this->config->item('allow_header')}"); // 允许任何访问(包括ajax跨域)
        header('Access-Control-Allow-Credentials: true');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        $msg = isset($this->_codeList[$code]) ? $this->_codeList[$code] : $msg;

        exit(json_encode(array(
            'data' => $data,
            'code' => intval($code),
            'msg'  => $msg,
        )));
    }

    /**
     * 是否已经登录 TODO
     */
    protected function _isLogined()
    {
        if(empty($this->userToken) || empty($this->userSecret))
        {
            return FALSE;
        }

        $this->load->model('AdminUserModel');
        if($this->AdminUserModel->isLogined($this->userToken, $this->userSecret))
        {
            return TRUE;
        }

        return FALSE;
    }

    /**
     * 校验参数情况
     * @param array $require
     * 传必填字段,格式为
     * array('column1' => '请选择填写column1', 'column2' => '请选择填写column2')
     * @return require提示的字段,默认code为1001
     */
    protected function _validate($require = array(), $method = 'post', $emptyRequire = array())
    {
        if($method == 'post')
        {
            $posts = $this->input->post();
        }
        elseif($method == 'get')
        {
            $posts = $this->input->get();
        }

        if(empty($posts))
        {
            return self::TEXT_NO_CONTENT;
        }
        if(!empty($require))
        {
            foreach($require as $key => $value)
            {
                if(!isset($posts[$key]) || $posts[$key] === '' || 
                    (is_array($posts[$key]) && empty($posts[$key])) || 
                    (in_array($posts[$key],$emptyRequire) && empty($posts[$key])) 
                  )
                {
                    return $value;
                }
            }
        }

        return TRUE;
    }

    /**
     * 格式化数组字段
     * @param array $data
     */
    private function _formatoutPutData(array &$data)
    {
        if(is_array($data) && !empty($data)){
            foreach ($data as $k => &$v){
                if(!is_array($v)){
                    $v = trim($v);
                }else{
                    $this->_formatoutPutData($v);
                }
            }
        }
    }

    /**
     * 根据token获取userId
     * @return boolean
     */
    private function _getUserIdByToken()
    {
        $this->load->model('AdminUserModel');
        return $this->AdminUserModel->getUserIdByToken($this->userToken, $this->userSecret);
    }

    /**
     * 判断是否超级管理员
     * @return boolean
     */
    private function _isSuper($userId)
    {
        $this->load->config('super_identity');
        $this->load->model('AdminUserModel');
        $info = $this->AdminUserModel->getUserInfo(array('id' => $userId, 'is_deleted' => 0, 'status' => 1), 'user_identity');

        if(!empty($info) && $info['user_identity'] === $this->config->item('super_identity'))
        {
            return TRUE;
        }
        return FALSE;
    }

    private function _getUserInfo($field = '')
    {
        $userId = $this->_getUserIdByToken();
        $fields = empty($field) ? 'username, system_id, ch_name, role_id' : $field;
        $info = $this->AdminUserModel->getUserInfo(array('id' => $userId, 'is_deleted' => 0), $fields);
        if($field)
        {
            return $info[$field];
        }
        return $info;
    }

    /**
     * 检查用户权限
     */
    private function _checkAccess($userId)
    {
        $urlAction = strtolower($this->router->class . '/' . $this->router->method);

        if($this->_isSuper($userId))
        {
            return TRUE;
        }

        $this->load->model('AdminUserModel');
        $userInfo = $this->AdminUserModel->getUserInfo(array('id' => $userId, 'is_deleted' => 0, 'status' => 0), 'system_id,department_id,role_id,privilege_id');
        if(!empty($userInfo))
        {
            $this->load->model('MenuModel');
            $menuWhere = array(
                'module' => $urlAction,
                'is_deleted' => 0,
                'status' => 1
            );
            $menuInfo = $this->MenuModel->getMenuInfo($menuWhere, 'id');
            if(!empty($userInfo['privilege_id']))
            {
                $arrPrivilegeId = explode(',', $userInfo['privilege_id']);
                if(!empty($menuInfo) && in_array($menuInfo['id'], $arrPrivilegeId))
                {
                    return TRUE;
                }
            }
            $this->load->model('RoleModel');
            $this->load->model('MenuModel');
            $roleWhere = array(
                'id' => $userInfo['role_id'],
                'system_id' => $userInfo['system_id'],
                'department_id' => $userInfo['department_id'],
                'is_deleted' => 0,
                'status' => 1
            );
            $roleInfo = $this->RoleModel->getRoleInfo($roleWhere, 'id');
            if(!empty($roleInfo))
            {
                $privilegeWhere = array(
                    'role_id' => $roleInfo['id'],
                    'is_deleted' => 0
                );
                $menuIds = $this->RoleModel->getPrivileges();
                if(!empty($menuIds) && in_array($menuInfo['id'], $menuIds))
                {
                    return TRUE;
                }
            }
        }

        return FALSE;
    }
};

完整Model类:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @property IMemcached $imemcached
 */
class MY_Model extends CI_Model
{
    protected $_cachePrefix = 'bg_web';
    public $table = '';
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        // $this->load->library('IMemcached');
        $this->load->library('Session');
        $this->load->config('siteinfo');

        $this->_cachePrefix = $this->_cachePrefix . '_';
    }

    /**
     * 执行sql查询 (不分页)
     * @param $table        查询表
     * @param $where 		查询条件[例`name`='$name']
     * @param $field       需要查询的字段值[例`name`,`gender`,`birthday`]
     * @param $limit       返回结果范围[例:10或10,10 默认为空]
     * @param $like         模糊查询使用[例:array('name' => 'test')]
     * @param $order       排序方式    [默认按数据库默认方式排序]
     * @param $group       分组方式    [默认为空]
     * @param $key          返回数组按键名排序
     * @return array        查询结果集数组
     */
    final public function my_select($table = '', $where = '', $field = '*', $limit = '', $like = array(), $order = '', $key='', $group = '') 
    {
        if(empty($table))
        {
            $table = $this->table;
        }
        if(!empty($where))
        {
            $where = $this->db->where($where);
        }
        $field = str_replace(",", ",", $field); // 替换掉中文字符
        $this->db->select($field);
        if(!empty($like) && is_array($like))
        {
            $this->db->like($like);
        }
        if(!empty($limit))
        {
            $limit_arr = explode(",", $limit);
            if(count($limit_arr)==1)
            {
                $this->db->limit($limit);
            }
            else
            {
                $this->db->limit($limit_arr[1], $limit_arr[0]);
            }
        }
        if(!empty($order))
        {
            $this->db->order_by($order);
        }
        if(!empty($group))
        {
            $this->db->group_by($group);
        }

        $this->db->from($table);
        $datalist = array();
        $query = $this->db->get();
        if ($query->num_rows() > 0)
        {
            foreach ($query->result_array() as $rs)
            {
                if($key) 
                {
                    $datalist[$rs[$key]] = $rs;
                } 
                else 
                {
                    $datalist[] = $rs;
                }
            }
        }

        $query->free_result();
        return $datalist;
    }

    /**
     * 获取分页列表
     * @param unknown $table
     * @param array $where
     * @param string $field
     * @param number $pageNo
     * @param number $pageSize
     * @param array $like
     * @param string $order
     * @param string $key
     * @return list: 返回结果集; page:当前页码;total:总页数
     */
    final public function my_listPager($table = '', $where = array(), $field = '*', $pageNo = 1, $pageSize = 15, $like = array(), $order = '', $key = '')
    {
        if(empty($table))
        {
            $table = $this->table;
        }
        $data = array(
            'list' => array(),
            'page' => $pageNo,
            'total' => 0
        );

        $offset = ($pageNo -1) * $pageSize;
        if(!empty($like))
        {
            $this->db->like($like);
        }
        $total = $this->db->where($where)->count_all_results($table);
        $result = $this->my_select($table, $where, $field, "{$offset}, {$pageSize}", $like, $order, $key);
        if($total > 0)
        {
            $data = array(
                'list' => $result,
                'total' => $total,
                'page' => $pageNo
            );
        }
        return $data;
    }

    /**
     * 根据条件获取单条查询记录
     * @param unknown $table
     * @param string $where
     * @param string $field
     * @return array    数据查询结果集,如果不存在,则返回空数组
     */
    final public function my_getOne($table = '', $where = '', $field = '*')
    {
        if(empty($table))
        {
            $table = $this->table;
        }
        $info = $this->my_select($table, $where, $field, '0, 1');
        if(!empty($info))
        {
            $info = $info[0];
        }

        return $info;
    }

    /**
     * 直接执行sql
     * @param unknown $sql
     * @return  boolean/query resource      如果为查询语句,返回资源句柄,否则返回true/false
     */
    final public function my_query($sql)
    {
        return $this->db->query($sql);
    }

    /**
     * 执行添加记录操作
     * @param unknown $table
     * @param unknown $data
     * @param string $returnInsertId
     */
    final public function my_insert($table = '', $data, $returnInsertId = TRUE)
    {
        if(empty($table))
        {
            $table = $this->table;
        }
        $this->db->insert($table, $data);
        if($returnInsertId)
        {
            return $this->db->insert_id();
        }
    }

    /**
     * 执行更新记录操作
     * @param $data        要更新的数据内容,参数可以为数组也可以为字符串,建议数组。
     *                      为数组时数组key为字段值,数组值为数据取值
     *                      为字符串时[例:`name`='phpcms',`hits`=`hits`+1]。
     *                      为数组时[例: array('name'=>'phpcms','password'=>'123456')]
     *                      数组的另一种使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
     * @param $where       更新数据时的条件,可为数组或字符串
     * @return boolean
     */
    final public function my_update($table = '', $data, $where)
    {
        if(empty($where))
        {
            return FALSE;
        }
        if(empty($table))
        {
            $table = $this->table;
        }
        $this->db->where($where);
        if(is_array($data))
        {
            foreach($data as $k=>$v)
            {
                switch (substr($v, 0, 2)) {
                    case '+=':
                        $this->db->set($k, $k."+".str_replace("+=","",$v), false);
                        unset($data[$k]);
                        break;
                    case '-=':
                        $this->db->set($k, $k."-".str_replace("-=","",$v), false);
                        unset($data[$k]);
                        break;
                    case '<>':
                        $this->db->set($k, $k."<>".$v, false);
                        unset($data[$k]);
                        break;
                    case '<=':
                        $this->db->set($k, $k."<=".$v, false);
                        unset($data[$k]);
                        break;
                    case '>=':
                        $this->db->set($k, $k.">=".$v, false);
                        unset($data[$k]);
                        break;
                    case '^1':
                        $this->db->set($k, $k."^1", false);
                        unset($data[$k]);
                        break;
                    case 'in':
                        if(substr($v, 0, 3)=="in("){
                            $this->db->where_in($k, $v, false);
                            unset($data[$k]);
                            break;
                        }else{
                            break;
                        }

                    default:
                        $this->db->set($k, $v, true);
                }
            }
        }

        return $this->db->update($table, $data);
    }

    /**
     * 删除数据 
     * @param unknown $table
     * @param unknown $where
     */
    final public function my_delete($table = '', $where)
    {
        if(empty($where))
        {
            return FALSE;
        }
        if(empty($table))
        {
            $table = $this->table;
        }
        return $this->db->delete($table, $where);
    }

    /**
     * 获取记录数
     * @param unknown $table
     * @param string $where
     */
    final public function my_total($table = '', $where = '')
    {
        if(empty($table))
        {
            $table = $this->table;
        }
        $info = $this->my_getOne($table, $where, "COUNT(*) AS n_total");
        return isset($info['n_total']) ? $info['n_total'] : 0;
    }

    /**
     * 获取某字段sum
     * @param unknown $table
     * @param unknown $field
     * @param string $where
     */
    final public function my_sum($table = '', $field, $where = '')
    {
        if(empty($table))
        {
            $table = $this->table;
        }
        $info = $this->my_getOne($table, $where, "SUM({$field}) AS n_sum");
        return isset($info['n_sum']) ? $info['n_sum'] : 0;
    }

    /**
     * 返回最后运行的查询(是查询语句,不是查询结果)
     * @return string
     */
    final public function my_lastQuery()
    {
        return $this->db->last_query();
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值