【问题标题】:Validating an array based on value根据值验证数组
【发布时间】:2019-04-01 14:07:49
【问题描述】:

我将一个对象传递给我的 Laravel 应用程序,该应用程序包含基于提供的另一个参数的 url 或字母数字输入。我不知道如何根据其他参数验证值。例如

feeds: [
  0: {source: "https://www.motorsport.com/rss/all/news/", type: "user", error: false}
  1: {source: "abc-news", type: "newsapi", error: false}
  2: {source: "the-verge", type: "newsapi", error: false}
]

所以在这种情况下,如果 type 是用户,我需要验证 URL,但如果是 newsapi,那么我需要使用正则表达式进行验证。

我正在使用Requests 中的规则以及要返回的错误消息来处理此问题。这是规则,显然最后 2 条代表我正在尝试做的事情,但没有检查类型的逻辑。

return [
    'name' => 'required|min:1|regex:/^[A-Za-z0-9_~\-!@#\$%\^&\(\)\s]+$/',
    'feeds.*.source' => 'url',
    'feeds.*.source' => 'min:1|regex:/^[A-Za-z0-9\-]+$/',
];

答案: 感谢@Ali 的回答,有了这些信息,我找到了这篇文章:How to use sometimes rule in Laravel 5 request class 并将我的请求更改为:

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
    return [
        'name' => 'required|min:1|regex:/^[A-Za-z0-9_~\-!@#\$%\^&\(\)\s]+$/'
    ];
}

/**
* Configure the validator instance.
*
* @param  \Illuminate\Validation\Validator  $validator
* @return void
*/
public function withValidator($validator)
{
    $validator->sometimes('feeds.*.source', 'url', function($data) {
        return $data->type=='user'; 
    });

    $validator->sometimes('feeds.*.source', 'min:1|regex:/^[A-Za-z0-9\-]+$/', function($data) {
        return $data->type=='newsapi';
    });
}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以使用有时验证规则来实现您想要的功能。在以下代码中,每次发出请求时都会验证代码名称​​,并根据类型验证源代码。

       $validator = Validator::make($data, [
                 'name' => 'required|min:1|regex:/^[A-Za-z0-9_~\-!@#\$%\^&\(\)\s]+$/',
    
                 ]); 
    
      $validator->sometimes('feeds.*.source','url',function($input){
            return $input->type=="user"; 
        });
    
        $validator->sometimes('feeds.*.source','min:1|regex:/^[A-Za-z0-9\-]+$/',function($input){
            return $input->type=="newsapi"
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 2020-06-29
      相关资源
      最近更新 更多