如何使用ajax提交的codeigniter中的form_validation验证表单数据

时间:2021-02-12 20:31:02

I'm writting a code using CodeIgniter

我正在使用CodeIgniter编写代码

ajax

阿贾克斯

  var formData = {};
  var url      = $(form_id).attr("action");
  $(form_id).find("input[name]").each(function (index, node) {
    formData[node.name] = node.value;
  });
  $(form_id).find('select[name]').each(function (index, node) {
    formData[node.name] = node.value;
  });
  $(form_id).find('textarea[name]').each(function (index, node) {
    formData[node.name] = node.value;
  });
  $.ajax({
    type: "POST",
    data: {
      'formdata': formData
    },
    url: url,
    dataType: 'json',
    success: function(result) {
      if (result.data) {
        make_alert();
      } else {
        $('#error-msg').html(result.message);
      }
    },
    error: function(result) {
     // error code here
    }
  });

Which will sent a data formData to add function in controller

这将发送一个数据formData来在控制器中添加功能

add function

添加功能

$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
        array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');

and this part here receive the formData values

这部分接收formData值

  $post_data = $this->input->post('formdata');
  $data = array (
    'username' => $post_data['username'],
    'email'    => $post_data ['email'],
    'password' => $post_data ['password']
  );

and this part run the validation

这部分运行验证

if ($this->form_validation->run() == FALSE) {
  $result['message'] = validation_errors();
} else {
  $result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
}

which return json

哪回归json

echo json_encode($result);

before using ajax, the code run smoothly without problem, but when using ajax, the validator return a message saying fields should be required, meaning, it doesn't receive form data submitted.

在使用ajax之前,代码运行顺利而没有问题,但是当使用ajax时,验证器会返回一条消息,说明应该需要字段,这意味着它不会收到提交的表单数据。

this part,

这部分,

  $data = array (
    'username' => $post_data['username'],
    'email'    => $post_data ['email'],
    'password' => $post_data ['password']
  );

when using var_dump() on $data show it received form data submitted using ajax.

当在$ data上使用var_dump()时,它会收到使用ajax提交的表单数据。

My question is, how to validate this $data using form_validation?

我的问题是,如何使用form_validation验证这个$ data?

1 个解决方案

#1


2  

You cant validate using form_validation library You should validate manually usin if statement and you will set error message as you want

您无法使用form_validation库进行验证您应该手动验证if语句,并根据需要设置错误消息

#1


2  

You cant validate using form_validation library You should validate manually usin if statement and you will set error message as you want

您无法使用form_validation库进行验证您应该手动验证if语句,并根据需要设置错误消息