1

I'm doing user editing facility for my admin panel. I want to ignore empty password on update, but not on create.

I have following validation rules for User model:

public static $rules = array(
    'login'                 => 'required|max:255|alpha_dash|unique',
    'displayname'           => 'required|max:255|unique',
    'email'                 => 'required|email|max:255|unique',
    'password'              => 'required|confirmed',
    'password_confirmation' => 'required',
);

But it doesn't let me update user model when I don't pass password to it. It just complains about not having a password.

How to make it work?

4

3 回答 3

3

您可以在控制器中执行以下操作:

if ($user->exists)
{
    $user::$rules['password'] = (Input::get('password')) ? 'required|confirmed' : '';
    $user::$rules['password_confirmation'] = (Input::get('password')) ? 'required' : '';
}

$user->save();
于 2014-01-08T18:18:12.783 回答
1

如果您想将此行为整合到模型本身(因此创建/保存它的位置无关紧要),您可以利用 Ardent 的beforeValidate功能在验证之前更改规则:

public function beforeValidate() { if(isset($this->id)) { self::$rules['password'] = 'confirmed'; self::$rules['password_confirmation'] = ''; } }

您只需在相关模型的任何位置添加类似的代码。

于 2014-11-13T21:11:22.827 回答
1

这是人们仍在思考的问题。但是通常创建规则和更新规则会有所不同。

public static $create_rules = array(
    'login'                 => 'required|max:255|alpha_dash|unique',
    'displayname'           => 'required|max:255|unique',
    'email'                 => 'required|email|max:255|unique',
    'password'              => 'required|confirmed',
    'password_confirmation' => 'required',
);

public static $update_rules = array(
    'login'                 => 'required|max:255|alpha_dash|unique',
    'displayname'           => 'required|max:255|unique',
    'email'                 => 'required|email|max:255|unique',
);

然后在您的验证码中,您可以

if ( ! $this->exists || Input::get('password'))
{
   $validation_rules = static::$create_rules;
}
else
{
   $validation_rules = static::$update_rules;
}
于 2014-01-08T18:21:16.320 回答