【问题标题】:Validate a field in Laravel only if it's zero or a value from db仅在 Laravel 中验证字段为零或来自 db 的值
【发布时间】:2016-04-26 05:01:46
【问题描述】:

我是 Laravel 新手,很抱歉我的新手问题:

我在输入字段中,只有当它为零或它的值存在于“产品”数据库表中时才有效。 我在 Laravel 5.2 中使用表单请求验证。

这是我的代码:

class CreateRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
      return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'product_id'    =>  'sometimes|exists:products,id'
        ];
    }
}

这适用于数据库验证,但如果它为零,我怎样才能使它有效?

感谢您的帮助!

【问题讨论】:

标签: validation laravel


【解决方案1】:

这可能会有所帮助

public function rules()
{
    return [
      'product_id' => 'integer|size:0|exists:products,id'
    ];
}

【讨论】:

    【解决方案2】:

    您必须创建自定义验证规则

    如果您使用的是 5.6,您可以创建自定义规则或传递闭包

       class CreateRequest extends Request
        {
            /**
             * Determine if the user is authorized to make this request.
             *
             * @return bool
             */
            public function authorize()
            {
              return true;
            }
    
    
        public function rules()
            {
                return [
                  'product_id'    =>  ['integer',  function($attribute, $value, $fail) {
    
                $product = Product::find($value);
                    if ($value != 0 && !$product  ) {
                        return $fail($attribute.' is invalid.');
                    }
                },
                ];
            }
         }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 2014-12-07
      • 2016-01-11
      • 2014-01-30
      • 1970-01-01
      • 2018-10-06
      相关资源
      最近更新 更多