codeigniter中编辑表单的有限验证

时间:2012-06-20 13:24:56

标签: php codeigniter

我正在使用带有codeigniter的模块化MVC。我有一个模块播放列表,其中我有一个管理控制器,我有一个私有$ rules变量,用于设置表单验证规则。

我在同一个文件中创建和编辑函数并验证两个表单(添加,编辑也是从一个文件form.php动态创建的)。

$this->load->library('form_validation');
$this->form_validation->set_rules($this->rules);
$this->form_validation->set_error_delimiters(' <p class="error">', '</p>');

这些用于创建和编辑功能。一些我不想在编辑模式下验证的字段。我是否需要为它们创建不同的私有规则,或者在codeigniter中有更好的方法来处理它,因为我是新手。我想删除 FILE标记的验证,因为用户无需在编辑模式下上传。

由于

1 个答案:

答案 0 :(得分:1)

以下是CI论坛(original link)的回答。

您可以使用某种形式的heirachy来定义创建/编辑的规则,然后;

<?php
$this->form_validation->set_group_rules('createModule');
$this->form_validation->set_group_rules('editModule');
if($this->form_validation->run() == FALSE) {
   // whatevere you want
}
?>

或者,你可以这样做;

<?php
// This will validate the 'accidentForm' first
$this->form_validation->set_group_rules('createModule');
if($this->form_validation->run() == FALSE) {
   // whatevere you want
}
// Now we add the 'locationForm' group of rules
$this->form_validation->set_group_rules('editModule');
// And now we validate *both* sets of rules (remember that the createModule rules are still
// there), but it doesn't necessarily matter, since it will simply redo the 'createModule'
// validation while also doing the 'editModule' validation
if($this->form_validation->run() == FALSE) {
   // whatevere you want
}
?>

下面是扩展Form_validation类的代码,保存在应用程序库文件夹中,作为MY_Form_validation.php

<?php
class MY_Form_validation extends CI_Form_validation {

    /**
     * Set Rules from a Group
     *
     * The default CodeIgniter Form validation class doesn't allow you to
     * explicitely add rules based upon those stored in the config file. This
     * function allows you to do just that.
     *
     * @param string $group
     */
    public function set_group_rules($group = '') {
        // Is there a validation rule for the particular URI being accessed?
        $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;

        if ($uri != '' AND isset($this->_config_rules[$uri])) {
            $this->set_rules($this->_config_rules[$uri]);
            return true;
        }
        return false;
    }

}

?>
相关问题