我在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);
}
Run Code Online (Sandbox Code Playgroud)
该表单是基于AJAX的,因此前端必须接收带有表单错误的JSON数组,例如:
array (
'email' => 'Bad email!',
'password' => '6 symbols only!',
)
Run Code Online (Sandbox Code Playgroud)
如何在CodeIgniter中获取具有表单验证错误的列表或数组?
mas*_*.mo 31
<?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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以从你的控制器尝试以下:
$errors = $this->form_validation->error_array();
Run Code Online (Sandbox Code Playgroud)
Tee*_*eej 21
你只需validation_errors()从控制器回复.
place在你的视图中有你的JavaScript .
PHP
// controller code
if ($this->form_validation->run() === TRUE)
{
//save stuff
}
else
{
echo validation_errors();
}
Run Code Online (Sandbox Code Playgroud)
使用Javascript
// jquery
$.post(<?php site_url('controller/method')?>, function(data) {
$('.errors').html(data);
});
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
Bre*_*cus 18
如果您更喜欢库方法,则可以扩展Form_validation类.
class MY_Form_validation extends CI_Form_validation {
public function error_array() {
return $this->_error_array;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的控制器/方法中调用它.
$errors = $this->form_validation->error_array();
Run Code Online (Sandbox Code Playgroud)
小智 8
使用最新版本的codeigniter:
print_r($this->form_validation->error_array());
Run Code Online (Sandbox Code Playgroud)
收益:
array("field"=>"message","field2"=>"message2");
Run Code Online (Sandbox Code Playgroud)