duansha6410 2014-04-18 23:03
浏览 131
已采纳

$ this-> form_validation-> run()返回FALSE而没有验证规则

When using CodeIgniter's Form_validation class, the set_rules() method allows a user to add an infinite number of checks to their form fields. These rules are usually all defined in the same place, right before the run() method is called.

VALID EXAMPLE:

// Require the user to be a werewolf.
$this->form_validation->set_rules('werewolf', 'Are you a Werewolf?', 'required');

// If the form validates.
if ($this->form_validation->run())
{
    // [...]

(no, I do not actually run a werewolf website)

The code makes a lot of sense, and is very easy to understand. However, at times, it may be undesirable. For example, perhaps you don't care if the user is a werewolf unless it is midnight. Your code would probably look like this:

INVALID EXAMPLE

// If it is midnight.
if (date('G') == '0')
{
    // Require the user to be a werewolf.
    $this->form_validation->set_rules('werewolf', 'Are you a Werewolf?', 'required');
}

// If the form validates.
if ($this->form_validation->run())
{
    // [...]

THIS WON'T WORK

At least, it won't work until midnight.

By default, $this->form_validation->run() returns FALSE if there aren't any rules declared. In the second example, unless it's midnight, there will not be any rules set, so the form will never validate. Logically, one would assume that if there are no rules, the form should validate no matter what. Instead, it fails no matter what.

/system/libraries/Form_validation :: run()

(lines 293-297)

// No validation rules?  We're done...
if (count($this->_config_rules) == 0)
{
    return FALSE;
}

My question is:

Why is this the default return value? Is it okay if I change it?

  • 写回答

2条回答 默认 最新

  • duanpo1821 2014-04-19 01:27
    关注

    @Nathanael - you are right, I can't recall without looking if this has been addressed in V3 or no.

    Two ways of dealing with this:

    1) (this won't work the way your code is currently set up, but w/ a small teak it will) - Set "trim" on every field, all the time. This will trigger all the validation code. It is an old workaround for repopulating forms even when you don't want to make anything required.

    2) Better - make a custom rule for that field that is ALWAYS checked, and require it conditionally inside the rule.

    Remember that validation library rules are actually just functions on the lib, so inside your custom rule you can do:

    $this->validation->required($str);
    

    type code to check your input.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块