【发布时间】: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';
});
}
【问题讨论】: