我正在尝试使用 codeigniter 的表单验证库来验证表单。我有一些问题,我需要帮助。
1.假设用户填写了一个表单进行提交。
2.验证库在数据库表中查找重复项并为字段设置错误消息。
3. 表单显示消息。
在这种方法中我看到了一个缺点。假设表中有 5 个字段设置为唯一。因此验证将运行查询来查找唯一字段 5 次。
另一种方法
就是让用户插入而db产生错误。表单验证库中没有调用这里的callback_find_duplicate函数。表单已填充。在这种方法中,很难找到哪个字段是重复的,因此为此设置错误消息会很麻烦。最糟糕的情况是该用户输入重复的名称。填写表格,然后填写电子邮件。然后是其他一些,然后继续。
我需要找到是否有办法或者我们可以编写一个查询来查找我所有字段的所有重复项。并为所有字段设置错误消息,而无需调用callback_find_duplicate五次。因为我认为调用单个查询将花费更少的执行时间。
最佳答案
尽管 form_validation 很伟大,但我发现自己有时更喜欢其他解决方案。
添加此:
库/My_Form_validation.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
/* Custom function to create errors manually
* */
function create_error($str_field, $str_message) {
$str_message = t($str_message, $str_line);
$this->_field_data[$str_field] =
array('error' => $str_message,
'is_array' => FALSE,
'postdata' => $this->CI->input->post($str_field),
'rules' => '',
'field' => $str_field);
$this->_error_array[$str_field] = $str_message;
}
}
然后您可以在 ->run()
之前在 Controller 中手动运行它。
根据需要获取查询,并为每种情况设置一个 if,如下所示:
$arr_uniques = array('email', 'name', 'snn'); // whatev
foreach($arr_uniques as $h)
if ($row->$h == $this->input->post($h))
$this->form_validation->create_error($h, "{$h} is not unique!");
关于mysql - Codeigniter 中的 mysql 错误表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10830255/