I'm passing an object to my Laravel application which contains either a url or alpha numeric input based on another parameter provided. I can't figure out how to validate the value based on the other parameter. E.g.
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}
]
So in this case, if the type is user, I need to validate the URL, but if it's newsapi then I need to validate with a regex.
I'm using the rules in Requests to handle this along with the error messages to be returned. Here's the rules, obviously the last 2 representing what I'm trying to do, but without the logic of checking the type.
return [
'name' => 'required|min:1|regex:/^[A-Za-z0-9_~\-!@#\$%\^&\(\)\s]+$/',
'feeds.*.source' => 'url',
'feeds.*.source' => 'min:1|regex:/^[A-Za-z0-9\-]+$/',
];
Answer: Thanks @Ali for the answer, with that info I was able to find this post: How to use sometimes rule in Laravel 5 request class and change my Request to:
/**
* 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';
});
}