我在我的CodeIgniter应用程序中有一个表单验证代码:
$this->load->library('form_validation');
$this->form_validation->set_rules('message', 'Message', 'trim|xss_clean|required');
$this->form_validation->set_rules('email', 'Email', 'trim|valid_email|required');
if($this->form_validation->run() == FALSE)
{
// some errors
}
else
{
// do smth
$response = array(
'message' => "It works!"
);
echo json_encode($response);
}表单是基于AJAX的,因此前端必须接收带有表单错误的JSON数组,例如:
array (
'email' => 'Bad email!',
'password' => '6 symbols only!',
)如何在CodeIgniter?中获得具有表单验证错误的列表或数组
发布于 2011-01-13 05:04:14
你只需从你的控制器中回音validation_errors()。
让您的javascript place它在您的视图。
PHP
// controller code
if ($this->form_validation->run() === TRUE)
{
//save stuff
}
else
{
echo validation_errors();
}Javascript
// jquery
$.post(<?php site_url('controller/method')?>, function(data) {
$('.errors').html(data);
});如果您真的想使用JSON,jquery会自动解析JSON。您可以遍历它并将append循环到html中。
如果需要将验证错误作为数组,可以将此函数附加到form_helper.php中。
if (!function_exists('validation_errors_array')) {
function validation_errors_array($prefix = '', $suffix = '') {
if (FALSE === ($OBJ = & _get_validation_object())) {
return '';
}
return $OBJ->error_array($prefix, $suffix);
}
}发布于 2011-12-17 04:20:07
应用程序/库/MY_Form_validation.php
<?php
class MY_Form_validation extends CI_Form_validation
{
function __construct($config = array())
{
parent::__construct($config);
}
function error_array()
{
if (count($this->_error_array) === 0)
return FALSE;
else
return $this->_error_array;
}
}然后,您可以从控制器中尝试以下操作:
$errors = $this->form_validation->error_array();参考资料:错误作为数组
发布于 2013-04-30 18:55:53
如果您希望使用库方法,则可以对Form_validation类进行扩展。
class MY_Form_validation extends CI_Form_validation {
public function error_array() {
return $this->_error_array;
}
}然后在控制器/方法中调用它。
$errors = $this->form_validation->error_array();https://stackoverflow.com/questions/4676915
复制相似问题