如何使 Laravel 的 Validator $rules 成为可选?

2021-12-26 00:00:00 validation php laravel laravel-4 eloquent

假设我有两种方法的 User 模型:

Let's say I have User model with two methods:

User.php

class User extends Eloquent
{  
    /* Validation rules */
    private static $rules = array(
        'user'  => 'unique:users|required|alpha_num',
        'email' => 'required|email'
    );

    /* Validate against registration form */
    public static function register($data)
    {
        $validator = Validator::make($data, static::$rules);
        if($validator->fails())
        {
            /*... do someting */
        }
        else
        {
            /* .. do something else */
        }
    }

    /* Validate against update form */
    public static function update($data)
    {
        $validator = Validator::make($data, static::$rules);
        if($validator->fails())
        {
            /*... do someting */
        }
        else
        {
            /* .. do something else */
        }
    }
}

我的问题:我怎样才能让验证规则成为可选的,所以即使 update() 的数据只是 email 字段,它会忽略 user 并仍然验证为 true.
这是可能的还是我遗漏了什么?

My question: How can I make validation rules optional, so even if data for update() would be just email field, it would ignore user and still validate to true.
Is this even possible or am I missing something?

抱歉我的英语不好.

推荐答案

不确定我的问题是否正确,但如果用户是可选的,则应从验证器中删除必需".这样你将有:

Not sure if I'm getting your question right but if the user is optional you should remove 'required' from the validator. This way you will have:

'user'  => 'unique:users|alpha_num',

代替:

'user'  => 'unique:users|required|alpha_num',

另一方面,我为我的模型创建了一个自定义方法,该方法能够根据传入参数返回自定义验证规则.

On the other hand I create a custom method for my models that is able to return custom validation rules depending on incoming parameters.

例如:

private function getValidationRules($rules)
{
    if ($rules == UPDATE_EMAIL)
    {
        return array('email' => 'required|email');
    } else {
        return array(
            'user'  => 'unique:users|required|alpha_num',
            'email' => 'required|email'
        );
    }
}

我想这只是个人选择,但我发现从方法中获取验证规则可以更好地控制我真正想要验证的内容,尤其是当您想要执行一些高级验证时.

I guess it's only a personal choice, but I have found that getting the validation rules from a method allows more control over what I really want to validate, especially when you want to perform some advanced validations.

希望对你有帮助.

相关文章