【问题标题】:CodeIgniter Form Validation Class - Handling errorsCodeIgniter 表单验证类 - 处理错误
【发布时间】:2014-04-16 23:23:55
【问题描述】:

所以我用 CodeIgniter 制作了一个表单,它确实使用了 CodeIgniter 的表单验证 类来验证输入字段。我总共有 6 个输入字段,它们都是 必填字段。

我什至想显示“此字段为必填项”的相同错误 如果有多个空字段,但现在它会为每个字段显示错误消息 的领域。因此,如果我将每个字段都留空,它将重复相同的消息 6 次。

我不会在这里粘贴任何代码,因为我知道如何使用实际的验证类,只是 不知道如何以上述方式实现它。

提前致谢!

E: 现在又来了一个问题,它没有显示任何错误,实际上整个方法在检查“add_user”按钮是否提交后就会失败。我 100% 确定我的提交按钮的名称是“add_user”。

抱歉缩进不好,我永远也学不会如何使用 StackOverflow 的缩进。

这是我添加用户的控制器:

<?php

    class Users extends CI_Controller {


    public function add_user() 
    {   



        if($this->input->post('add_user'))
        {   

            $this->load->model('subject');

            $data['subjects'] = $this->subject->get_all_subjects();
            $data['schools'] = $this->subject->get_all_schools();


            $this->load->library('form_validation');

            $this->form_validation->set_rules('f_name', 'Etunimi', 'required');
            $this->form_validation->set_rules('l_name', 'Sukunimi', 'min_length[3]');
            $this->form_validation->set_rules('email', 'Sähköpostiosoite', 'matches[email_confirm]|is_unique[users.email]|valid_email');
            $this->form_validation->set_rules('email_confirm', 'Sähköpostiosoite', 'valid_email');
            $this->form_validation->set_rules('phone_number', 'Puhelinnumero', 'min_length[7]|max_length[10]');

            if($this->input->post('user_type') == "moderator")
            {   
                $this->load->library('form_validation');

                $this->form_validation->set_rules('school', 'Koulutalo', 'required');
                $this->form_validation->set_rules('subject', 'Laji', 'required');

            }

            $this->form_validation->set_message('required', 'Täyttämättömiä kenttiä');
            $this->form_validation->set_message('min_length', '%s - kentässä on liian vähän merkkejä');
            $this->form_validation->set_message('matches', 'Sähköpostit eivät täsmää');
            $this->form_validation->set_message('is_unique', '%s on jo rekisteröity');

            if($this->form_validation->run() == FALSE)
            {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('result' => 0, 'error' => $this->form_validation->error_array() )));
                return false;

            }


            $first_part_username = substr($this->input->post('f_name'), 0, 2);
            $second_part_username = substr($this->input->post('l_name'), 0, 3);

            $first_part_username = strtolower($first_part_username);
            $second_part_username = strtolower($second_part_username);

            $this->load->helper('string');

            $random_number = random_string('numeric', 4);

            $username = $first_part_username . $second_part_username .$random_number;


                $password = random_string('alnum', 8);

                $this->load->model('user');

                $name = ucfirst($this->input->post('f_name')). " " .ucfirst($this->input->post('l_name'));

                $data = array (
                'name'      => $name,
                'email'     => $this->input->post('email'),
                'username'  => $username,
                'password'  => $this->phpass->hash($password),
                'user_type'     => $this->input->post('user_type'),
                'phone_number'  => $this->input->post('phone_number'),
                'subject_id'    => !($this->input->post('subject')) ? null : $this->input->post('subject'),
'school_id' => !($this->input->post('school')) ? null : $this->input->post('school')
                    );


            $this->user->add_user($data);
        $this->load->library('email');

            $config['mailtype'] = 'html';
            $this->email->initialize($config);

            $this->email->from('your@example.com', 'Your Name');
            $this->email->to($this->input->post('email'));  
            $this->email->subject('test test');
            $this->email->message('Test');

            if($this->email->send()) {

                $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('result'=>1, 'msg' => 'Uusi käyttäjä lisätty')));
            }
        }

            /* It will echo out this one which is viewable from developer tab right after the form is submitted */

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('result'=>1, 'msg' => 'Form not submitted')));
    }
}
?>

还有 javascript:

$(document).ready(function() {

        $("#add_user_form").on('submit', function(e) {

            e.preventDefault();

                $("#loading_spinner").show();
                var from = $(this);

                $.ajax({

                    url: from.attr('action'),
                    type: from.attr('method'),
                    data: $(from).serialize(),
                    }).done(function(data) {



                    if(data.result == 0) {

                        $("#forgot-pass-success").hide();
                        $("#forgot-pass-error").show();
                        $("#forgot-pass-error").fadeIn(1000).html("<p>" + data.error + "</p>");

                      }

                    if(data.result == 1) {

                        $("#forgot-pass-error").hide();
                        $("#forgot-pass-success").show();
                        $("#forgot-pass-success").fadeIn(1000).html("<p>" + data.msg + "</p>");
                      }

                   $("#loading_spinner").hide(); 

                }, 'json');

            return false;

        });
});

【问题讨论】:

  • 您必须在您的 javascript 中循环从 PHP 发送的数组以显示每个错误 btw。我还在看你的代码。
  • $this->load->library('form_validation');只需在该函数中加载一次即可为整个函数工作。所以你可以删除重复项。
  • 完成了这些。现在它每次都会将“表单未提交”作为 JSON 回显。所以基本上 AJAX 部分在获取这些 JSON 时是有效的。
  • 是的,现在改变这个 $this->output->set_output(json_encode(array('result' => 0, 'error' => $this->form_validation->error_array() ))) ; TO $this->output->set_output(json_encode(array('result'=>1, 'msg' => $this->form_validation->error_array())));所以它符合你的方案
  • 您对 JSON 的看法是正确的,添加的 JSON 需要更改为 msg,以便我们可以在您的输出中看到它。

标签: php forms codeigniter validation


【解决方案1】:

这是一个返回 JSON 字符串中的错误以使用 jQuery 处理的示例,您必须加载表单验证帮助程序。

加载库:

$this->load->library('form_validation');

        /* Outputto Json Format */
        $this->output->set_content_type('application_json');
        /* Validate Form Data */
        $this->form_validation->set_rules('login', 'Username', 'required|min_length[4]|max_length[16]|is_unique[user.login]');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user.email]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_lenght[6]|max_length[16]|matches[confirm_password]');
        /* Custom Messages */
        $this->form_validation->set_message('required', 'You must enter a %s.');
        $this->form_validation->set_message('is_unique', 'That %s is already in use, please try again.');
        $this->form_validation->set_message('valid_email', 'You must enter a vaild email address.');

        if($this->form_validation->run() == false)
        {
            $this->output->set_output(json_encode(['result' => 0, 'error' => $this->form_validation->error_array()]));
            return false;
        }

$login = $this->input->post('login');
        $email = $this->input->post('email');
        $password = $this->input->post('password');
        $confirm_password = $this->input->post('comfirm_password');

        $user_id = // DO YOUR QUERY HERE


        if($user_id)
        {
            $this->session->set_userdata(['user_id' => $user_id]);
            $this->output->set_output(json_encode(['result' => 1]));
            return false;
        }
        $this->output->set_output(json_encode(['result' => 0, 'error' => 'User not created.']));

编辑: 抱歉,我正在使用自定义库来扩展 form_validation,以便创建要返回的数组。只需确保将其保存在库文件中为 my_form_validation.php

class MY_Form_validation extends CI_Form_validation
{
    // ------------------------------------------------------------------------

    public function __construct($config = array())
    {
        parent::__construct($config);
    }

    // ------------------------------------------------------------------------

    public function error_array()
    {
        if(count($this->_error_array > 0))
        {
            return $this->_error_array;
        }
    }

    // ------------------------------------------------------------------------
}

编辑:在 jQuery 中处理此数据的示例

<!-- Javascript POST -->
<script type="text/javascript">
    $(function() {
        // You need to create a div called #register_form_error
        $("#register_form_error").hide();
        // Your register form would go here in place of #regiser_form
        $("#register_form").submit(function(evt) {
            evt.preventDefault();
            var url = $(this).attr('action');
            var postData = $(this).serialize();

            $.post(url, postData, function(o) { 
                if (o.result == 1) {
                    // If the registration was successful where to go.
                    window.location.href = '<?=site_url('where to go')?>';
                } else {
                    // This is where all of the form errors will be displayed
                    $("#register_form_error").show();
                    var output = '<ul>';
                    for (var key in o.error) {
                        var value = o.error[key];
                        output += '<li>' + value + '</li>';
                    }
                    output += '</ul>';
                    $("#register_form_error").html(output);
                }
            }, 'json');

        });

    });
</script>

最后:

if($this->input->post('add_user'))

应该是:

if($this->input->post('$_POST'))

这样你就得到了整个帖子数组。

【讨论】:

  • $this->output->set_output(json_encode(['result' => 0, 'error' => $this->form_validation->error_array()]));
  • @B_CooperA 对不起,我忘了我扩展了默认的 form_validation,我编辑了我的帖子,所以你也可以使用它。
  • 我很困惑。我已经完成了你上面提到的一切,但代码仍然被破坏(只是得到一个空白页)。我已经复制了您的扩展库,将其放在 application/libraries 文件夹中,将其保存为 my_form_validation.php 并自动加载 form_validation
  • 如果您使用的是谷歌浏览器,您可以按 ctrl+shift+i 打开开发者控制台,在网络选项卡下您将能够看到访问的页面。您将看到该请求,您需要单击该请求并查看来自服务器的响应以查看发生了什么。如果您从中获得信息以及它是什么,请告诉我。
  • 另外请记住,这是返回一个 JSON 编码的字符串,您必须使用 jQuery 对其进行解析。所以你不能只是盲目地复制粘贴这段代码,因为它不会那样工作。
【解决方案2】:

在我的脑海中,您可以尝试使用个别错误。

在你看来:

<?php
    $form_errors = array(
        form_error('field_1'),
        form_error('field_2'),
        form_error('field_3'),
        form_error('field_4'),
        form_error('field_5'),
        form_error('field_6')
    );

    $error = FALSE;

    foreach ($form_errors as $form_error)
    {
        if ( ! empty($form_error))
            $error = TRUE;
    }

    if ($error)
        echo "All fields are required".
?>

所以基本上你在这里所做的是填充一系列单独的表单错误。 form_error()根据校验规则填写正确则返回空字符串,否则报错。

为了确认所有内容都正确填写,您正在寻找一个空字符串数组。如果某个字段未正确填写,您的数组将包含一个包含错误消息的元素。

【讨论】:

    猜你喜欢
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2013-01-17
    • 2013-03-24
    相关资源
    最近更新 更多