【问题标题】:CodeIgniter validating drop down menuCodeIgniter 验证下拉菜单
【发布时间】:2012-08-22 06:06:42
【问题描述】:

如果选项等于“选择”,我将如何在 CodeIgniter 中编写代码抛出一个错误,提示需要选择一个选项?

<option>Select</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>

非常感谢。

【问题讨论】:

标签: php codeigniter


【解决方案1】:
<select id='my_options'>
<option value=0>Select</option>
<option value=1>Option 1</option>
<option value=2>Option 2</option>
<option value=3>Option 3</option>
<option value=4>Option 4</option>
</select>

在你的控制器中你可以这样做:

$this->form_validation->set_rules('my_options','Select Options','required|greater_than[0]');

显然,这假设您正在使用 form_validation 类,并且您的表单被定向到一个控制器,您将在其中编写上述代码行..这样可以吗?

【讨论】:

    【解决方案2】:

    据我所知,处理这种情况的唯一方法是创建自定义函数。使用它并不难,例如:

    首先,为form_validation库创建规则:

    $this->form_validation->
    set_rules('my_dropdown', 'Dropdown', 'callback_my_func');

    其中my_func 是返回true 或false(以及错误消息)的验证函数。

    下面是my_func 的示例:

    注意:您必须指定每个选项的值,以便使用它们。
    在我的示例中,您将“选择”选项设置为 0。通过执行以下操作:

    &lt;option value="0"&gt;Select&lt;/option&gt;

    ...函数如下:

     function my_func($dropdown_selection){
    //If the selection equals "Select" that means it equals 0(which is the "hidden" value of it)
        if($dropdown_selection === 0) {
        //Set the message here.
        $this->form_validation->set_message('my_func', 'You must specifiy a value for your dropdown');
        //Return false, so the library knows that something  is wrong.
        return FALSE;
        }
        //If  everything is OK, return TRUE, to tell the library that we're good.
        return TRUE:
    
        }
    

    此代码应该可以工作,但未经测试。您始终可以发挥创意并添加更多代码并将其定制到您的特定网络应用程序。有关详细信息,请查看 CI 的有关 form_validation 库的文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多