I'm making an API and I'm having trouble finding the right validation rule when making a request with a parameter indicating the order.
The order in which they could ask for the results can be of a given number of values. Let's say as an example that the possible values are: name, postalcode and age
And that order could be ascending or descending, and could result in requests like these:
https://www.example.com/api/v1/users?sort=name,-postalcode,-age
I'm trying to find the right validation rule but so far I haven't succeeded.
The problem I am facing is the possible concatenation of the - character and the , together with the fact that the fields must have a suitable value among some possible values. That is, I don't know how to put the rules together:
$validation = Validator::make($request->all(),[
'sort' => 'sometimes|regex:/(^-?+(name|postalcode|age)+(,)?+(-)?){1,}/',
]);
I guess the rule would be something like:
- There can be an optional
-character - followed by one of these values:
name,postalcodeorage. - Followed by a character
,(only if there is a character after it) - And all this can be repeated one or more times.
Please could you help me to find out what the appropriate validation rule should be, or at least give me some guidance.
Thank you very much in advance.
https://www.example.com/api/v1/users?sort[]=name&sort[]=-postalcodesort[]=-ageThat would simplify the validation a lotacceptedfield names which you use to compare the incoming against. If it is not in the list, ignore it rather than throwing a validation error.