dopcpc9207 2012-08-21 12:08
浏览 53
已采纳

Codeigniter表单验证库

I am using the form validation library however I have come across something I cannot work out how to do.

I have several fields,

I have:

  • page_title => required
  • menu_title => not required
  • parent_id => null or required

Now if menu_title is not set then it should take on the value of page_title.
Then, I need to do a check to make sure that, at the given level the menu_title is unique.

So,

if($menu_title == '')
    $menu_title = $page_title;

return $this->db->
select('menu_title')->
from('cart_categories')->
where(array('menu_title' => $menu_title,
            'parent_id' => $category_parent))->
get()->num_rows() == 0;

But I don't know how to actually use that in the form validation library?

  • 写回答

1条回答 默认 最新

  • douyan2821 2012-08-21 12:34
    关注

    You'll need to use a callback function in order to do that. Just define one (changed code around slightly to fit formatting). Note, this is off the top of my head (and the docs):

    public function check_title($string) {
        $this->db->select('menu_title')->from('cart_categories');
        $this->db->where(array('menu_title' => $string,'parent_id' => $this->input->post('category_parent')));
        if ($this->db->get()->num_rows() != 0 {
            $this->form_validation->set_message('check_title', '%s must be unique');
            return FALSE;
        }
        return TRUE;
    }
    

    Then set the input for that particular field to use the callback:

    $this->form_validation->set_rules('menu_title', 'Menu Title', 'callback_check_title');
    

    I think you can add an additional underscore to the left side of the callback function name to make sure CI does not route it (as it is public), and just reflect that where you enter the callback name to the rules. I'm not positive about that, though.

    As far as passing the additional field as the callback only takes the string, you could just set a class variable.

    You can also just handle the validation yourself, which might be cleaner in your case.

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

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流