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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用