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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化