【问题标题】:Laravel's "require_if" field value is contained within an arrayLaravel“required_if”字段值包含在数组中
【发布时间】:2013-07-30 21:48:42
【问题描述】:

在我的控制器的“存储”(POST) 函数中,我想验证一个特定的输入字段。我有一个字段listPrice,仅当另一个字段vendor 的值在数组中时才需要。供应商数组需要从单独的服务调用中填充。所以,我的问题有两个:

  1. 如果vendor 的值包含在数组中,我如何编写验证规则以要求listPrice 并且
  2. 什么时候填充供应商的数组?它会在store() 函数内并在每次调用该函数时运行吗?验证规则位于控制器类的私有数组中,因此我相信它只会创建一次,而不是每次调用 store() 函数时。

【问题讨论】:

    标签: php validation laravel laravel-4


    【解决方案1】:

    1。 如果您可以从 laravel 的验证器访问 $this[data],这将相当简单,但如果您只是将 Validator::extend 用于您的自定义规则,我不相信您可以。您也不能从您的规则中访问其他验证规则,这可能在这里派上用场。所以最干净的可能是扩展验证器类。

    class CustomValidator extends Illuminate\Validation\Validator {
    
        public function validateIfInVendorArray($attribute, $value, $parameters)
        {
        $other = $parameters[0];
        $vendor = $this->data[$other];
    
        //populate your array from your service call, then check if present
        $vendorArray = your service call or wherever you have it;
    
        //if in array, return the result of the Validator's validateRequired method, which we can access since it's protected in Validator        
        if (in_array($vendor,$vendorArray))
            return $this->validateRequired($attribute,$value);
    
        //if it wasn't in the array, return true to pass validation even if it doesn't exist
        return true;
        }
    }
    

    记得也要register your custom validator resolver

    要使用您的规则,您只需将供应商字段的属性名称作为参数传递。

    2。 我认为这取决于需要阵列的位置以及频率。

    如果仅需要此验证,我会在您的自定义验证规则中执行此操作,以避免为控制器堆积更多工作。

    我个人会将验证规则移至自定义验证器类,然后您可以将供应商数组作为该自定义验证器的字段。然后,此自定义验证器类将成为您的控制器使用的服务,请参阅 https://tutsplus.com/lesson/validation-services/ 以获得一个很好的示例。

    我自己没有测试过这些,但我相信它应该可以工作!抱歉,如果这不是最优雅的解决方案。

    【讨论】:

    • 嗨@pfrendly:我正在遵循您建议的解决方案。这很好,但面临一个问题。 Fox 示例,如果我像这样使用它:'field_name' => 'required|if_in_vendor_array:vendor_field' 它正在工作,但 'field_name' => 'if_in_vendor_array:vendor_field' 不起作用......可能是什么原因?
    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2020-01-24
    • 2017-06-27
    • 2017-01-14
    • 2019-06-07
    • 2018-11-14
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多