doukai2839 2012-06-12 02:28
浏览 50
已采纳

在CodeIgniter中设置表单验证规则而不重复代码

How do I set validation rules in codeIgniter if the inputs have same validation rules like in this case its required.

            $this->form_validation->set_rules('username', 'Username', 'required');
            $this->form_validation->set_rules('password', 'Password', 'required');
            $this->form_validation->set_rules('firstname', 'Firstname', 'required');
            $this->form_validation->set_rules('middlename', 'Middlename', 'required');
            $this->form_validation->set_rules('lastname', 'Lastname', 'required');
  • 写回答

1条回答 默认 最新

  • douzhicai7148 2012-06-12 02:39
    关注

    you can simply make an array of fields and then iterator over the array

    $fields = array('username' => 'Username', 'password' => 'Password', 'firstname' => 'Firstname');
    foreach($fields AS $key=>$val){
     $this->form_validation->set_rules($key, $val, 'required')
    }
    

    next time, you just need to add new item(s) to the $fields array and it will auto add validation rules for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?