I'm writting a code using 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
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
$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
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.
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.
My question is, how to validate this $data
using form_validation?
您无法使用form_validation库进行验证您应该在if语句中手动验证,然后根据需要设置错误消息
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.