Form_validation不使用配置文件中的规则(CodeIgniter 2)

时间:2011-01-18 00:53:48

标签: validation file forms codeigniter config

我的表单验证未使用CodeIgniter 2中config file中的规则。我正在访问/ admin / people / add和/ admin / people / edit / id 并提交给/ admin / people / save。当我提交添加表单时,它只是重新加载添加而不报告任何验证错误(如果$ this-> form_validation-> _error_array不为空,我的表单视图将显示验证错误;这适用于我的登录表单)。当我提交编辑表单时,我在/ admin / people / save时收到404错误,即使该URI在我最初进入编辑页面时仍然有效。我正在构造函数中加载表单验证库。

应用/配置/ form_validation.php:

<?php  if(!defined('BASEPATH')) exit('No direct script access allowed');
$config = array(
    'people/save' => array(
        array(
            'field' => 'first_name',
            'label' => 'first name',
            'rules' => 'trim|required'
        )
    ) // people/save
);
/* End of file form_validation.php */
/* Location: /application/config/form_validation.php */ 

应用/控制器/管理/ people.php:

public function add() {
    $fields = $this->db->list_fields('people');
    /* set_defaults makes an object with null values for the fields in the database */
    $person = $this->form_validation->set_defaults($fields);
    $data = array(
        'action' => 'add',
        'person' => $person,
        'button_text' => 'Add Person'
    );
    $data['page_type'] = 'form';
    $this->layouts->set_title('Add a Person');
    $this->layouts->view('people/add_edit_person_form',$data);
} // add

public function save(){
    if($this->form_validation->run('people/save') == FALSE){
        if(is_numeric($this->input->post('person_id'))){
            $this->edit();
        } else {
            $this->add();
        }
    } else {
        redirect('people'); // test to see if it's passing validation
    }
} // save 

应用/视图/ add_edit_person_form.php:

<?php
$attributes = array(
    'class' => 'block',
    'id' => 'add_edit_person'
);
echo form_open('admin/people/save');
?>
<div class="required<?php echo form_error('first_name')?' error':'';?>">
    <label for="first_name">First name:</label>
    <input name="first_name" id="first_name" type="text" value="<?php echo set_value('first_name',$person->first_name); ?>" size="75" maxlength="255" />
</div>

<input name="person_id" id="person_id" type="hidden" value="<?php echo set_value('id',$person->id); ?>" />
<button><?php echo $button_text; ?></button>

</form> 

1 个答案:

答案 0 :(得分:2)

$config中定义application/config/form_validation.php数组后,您需要调用以下函数来设置规则:

$this->form_validation->set_rules($config);

参考:Setting Rules Using an Array