1

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';
    });
}

1 Answer 1

2

You can use sometimes validation rule to achive your desired functionality. In the following code name will be validated every time when you make a request and source will be validated based on the type.

   $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"
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.