【问题标题】:Laravel 5.2 validation check if value is not equal to a variableLaravel 5.2验证检查值是否不等于变量
【发布时间】:2016-04-22 21:38:12
【问题描述】:

在我的例子中,一个用户正在邀请另一个用户我想检查他们邀请的用户是否不是他们自己。

因此我有两个变量 incomming emailuser->email

$this->validate($request, [
            'email' => 'required|email',
        ]);

如何将该验证规则添加到验证调用中?

【问题讨论】:

    标签: php validation laravel laravel-5.2


    【解决方案1】:

    您可以使用not_in,它允许您指定要拒绝的值列表:

    $this->validate($request, [
        'email' => 'required|email|not_in:'.$user->email,
    ]);
    

    【讨论】:

    • 非常感谢。我浪费了一个小时来寻找解决方案。
    【解决方案2】:

    你可以根据laravel Document使用different:field

    例如在您的请求验证中:

    public function rules()
        {
            return [
                'from' => 'required',
                'to' => 'required|different:from',
                'action' => 'required',
                'access' => 'required'
            ];
        }
    

    这两个fromto 应该不同(不一样)。

    【讨论】:

    • different:from 有一个小的棘手时刻,至少对于 laravel 5.8。情况是,如果 from 将是 from='3'to=3,它们将被视为不同。
    【解决方案3】:

    正如@Vlad Barseghyan 在接受的答案中提到的那样:

    情况是,如果 from 将 from='3' 和 to=3,它们将被视为不同。

    这是因为different 验证规则如何比较给定字段。它使用严格的比较,在某些情况下处理integers 时会导致意外行为。

    not_in 规则使用松散比较,可用于完成与different 规则相同的行为。

        public function rules()
        {
            return [
                'from' => 'required',
                'to' => 'required|not_in:' . $this->from,
                'action' => 'required',
                'access' => 'required'
            ];
        }
    
    
        public function messages()
        {
            return [
                'to.not_in' =>
                    'to and from should be different.'
            ];
        }
    

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 2015-05-25
      • 2019-11-17
      • 2020-01-05
      • 2021-03-28
      • 2012-10-16
      • 2015-02-04
      • 2011-11-20
      相关资源
      最近更新 更多