Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php CodeIgniter表单验证,无法获取验证错误_Php_Forms_Codeigniter_Validation - Fatal编程技术网

Php CodeIgniter表单验证,无法获取验证错误

Php CodeIgniter表单验证,无法获取验证错误,php,forms,codeigniter,validation,Php,Forms,Codeigniter,Validation,我正在尝试使用CodeIgniters表单验证库,尽管我的验证规则似乎有效,但无论何时调用validation_errors(),我都会得到一个空字符串 下面是一段代码片段 $base_rules = 'required|trim'; $this->_validation_rules = array( array( 'field' => 'name', 'label' => 'name',

我正在尝试使用CodeIgniters表单验证库,尽管我的验证规则似乎有效,但无论何时调用validation_errors(),我都会得到一个空字符串

下面是一段代码片段

$base_rules = 'required|trim';

$this->_validation_rules = array(
        array(
            'field' => 'name',
            'label' => 'name',
            'rules' => $base_rules . '|alpha_numeric|min_length[5]|max_length[30]'
        ),
        array(
            'field' => 'price',
            'label' => 'Price',
            'rules' => $base_rules . '|decimal'
        ),
        array(
            'field' => 'duration',
            'label' => 'Duration',
            'rules' => $base_rules . '|integer'
        ),
        array(
            'field' => 'booking',
            'label' => 'Booking',
            'rules' => $base_rules . '|integer'
        )
    );
    $this->form_validation->set_rules($this->_validation_rules);

    if ($this->form_validation->run()) {
        // do stuff
    }else{
        // prints an empty string
         var_dump(validation_errors());
         exit;
    }
有人知道为什么会出现这种情况,以及我如何获得错误吗?

将validation\u errors()放在表单的顶部,并将代码更改为

 if ($this->form_validation->run()) {
        // do stuff
    }else{
       $this->load->view('myform'); //display your form again
    }

验证错误()只会在视图中显示。

将此代码放在视图文件的表单顶部

echo validation_errors('<div>', '</div>');

要完成John的回答,如果你做了一个表单帖子,你可以在你的输入下:

<?php echo form_error('input-name'); ?>
然后在客户端,您可以使用如下响应:

error:function(data) {
    $("your-error-input-selector").html('').append(data.responseJSON.msg);
}
希望我能帮忙,即使我晚了一年


p.S抱歉我的英语不好。

非常感谢,但有一个问题-这是否意味着无法将验证错误存储在flashdata或其他存储中,以便我可以重定向到其他地方?Cheers@John如果我们发送一个AJAX请求呢?当然,然后我们需要在控制器而不是视图中获取错误。那个么,有并没有解决控制器中出现错误的方法呢<代码>验证\u错误()在控制器中不工作。是否添加了表单验证?你进行了验证吗?我可以看一下你的密码吗?我非常乐意帮助你!
    //Important to turn that off if it's on
    $this->output->enable_profiler(false); 

    $this->output->set_status_header('500');
    $this->output->set_content_type('application/json');

    echo json_encode(array(
        'error_msg' => validation_errors(),
    ));
error:function(data) {
    $("your-error-input-selector").html('').append(data.responseJSON.msg);
}