Form_validation错误放入数组 [英] Form_validation errors into array

查看:78
本文介绍了Form_validation错误放入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在CodeIgniter应用中有一个用于表单验证的代码:

I have a code for form validating in my CodeIgniter app:

$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数组格式错误,例如:

The form is AJAX-based, so frontend have to receive a JSON array with form errors, for example:

array (
  'email' => 'Bad email!',
  'password' => '6 symbols only!',
)

如何在CodeIgniter中获取带有表单验证错误的列表或数组?

推荐答案

您只是回显 validation_errors()从您的控制器。

You just echo validation_errors() from your controller.

有您的JavaScript 位置

have your javascript place it in your view.

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。您可以遍历它,然后追加到您的html中。

If you really want to use JSON, jquery automatically parses JSON. You can loop through it and append into your html.

如果您需要验证错误作为数组,则可以将此函数附加到form_helper.php

in case you need validation errors as array you can append this function to the 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);
   }
}

这篇关于Form_validation错误放入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆