为什么这个函数能够在不使用Validator类的情况下验证用户输入?

时间:2015-01-14 12:51:05

标签: validation laravel laravel-4 laravel-validation

我正在研究Laravel application,我在这个应用程序中发现了一些奇怪的行为。

此应用程序中有一些Web表单。大多数处理POST请求的控制器方法使用Validator::make()来验证用户输入,但我发现有两种方法根本不使用Validator::make()

起初我认为这两种形式没有输入验证。然而,令人惊讶的是,我发现Web表单仍然能够验证用户输入。

示例1: (使用Validator)

  1. Controller Method 1(第60-67行)
  2. Controller Method 2(第62-68行)

  3. $rules = array(
        'title'   => 'required|min:3',
        'content' => 'required|min:3'
    );
    ...
    $validator = Validator::make(Input::all(), $rules);
    

    示例2: (不使用验证器)

    1. Controller Method 3(第89 - 111行)
    2. Controller Method 4(第27-47行)

    3. $this->user->username = Input::get( 'username' );
      $this->user->email = Input::get( 'email' );
      $this->user->password = Input::get( 'password' );
      ...
      $this->user->save();
      

      我想知道为什么示例2 中的函数能够在不使用Validator的情况下验证用户输入?

1 个答案:

答案 0 :(得分:2)

此应用程序的用户模型使用ConfideUser特征。如果我们看一下trait in the confide package,我们可以看到有一个save()方法覆盖了Laravel中的默认方法。

/**
 * Overwrites the original save method in order to perform
 * validation before actually saving the object.
 *
 * @param array $options
 *
 * @return bool
 */
public function save(array $options = array())
{
    if ($this->isValid()) {
        return parent::save($options);
    }
    return false;
}

它会调用$this->isValid(),只有在一切正常时才会保存。这里是isValid()

/**
 * Checks if the current user is valid using the ConfideUserValidator.
 *
 * @return bool
 */
public function isValid()
{
    // Instantiate the Zizaco\Confide\UserValidator and calls the
    // validate method. Feel free to use your own validation
    // class.
    $validator = App::make('confide.user_validator');
    // If the model already exists in the database we call validate with
    // the update ruleset
    if ($this->exists) {
        return $validator->validate($this, 'update');
    }
    return $validator->validate($this);
}

它创建了一个confide自己的UserValidator实例,并使用它来验证当前模型。

相关问题