3

I am trying to validate a payment methods field.

Requirement is the field under validation must be of type array (Multiple values allowed) and the items should not be other than the defined option

'payment_method' => 'required|array|in:american_express,cash_on_delivery,paypal,paypal_credit_card,visa_master_card'

So the user should pass an array of values for e.g

array('american_express','paypal');

But should not pass

array('american_express', 'bank');

I am unable to find any such method in Laravel 4.1 documentation. Is there any work around for this ?

2 Answers 2

4

If you're using a later version of Laravel (not sure when the feature becomes available - but certainly in 5.2) you can simply do the following:

[
    'payment_method' => 'array',
    'payment_method.*' => 'in:american_express,cash_on_delivery,paypal,paypal_credit_card,visa_master_card'
];

You check that the payment_method itself is an array if you like, and the star wildcard allows you to match against any in the array input.

You might consider putting this into the rules() method of a request validator (that you can generate with php artisan make:request PaymentRequest as an example.

Sign up to request clarification or add additional context in comments.

Comments

2

You can actually extend the Laravel validator and create your own validation rules. In your case you can very easily define your own rule called in_array like so:

Validator::extend('in_array', function($attribute, $value, $parameters)
{
    return !array_diff($value, $parameters);
});

That will compute the difference between the user input array found in $value and the validator array found in $parameters. If all $value items are found in $parameters, the result would be an empty array, which negated ! will be true, meaning the validation passed. Then you can use the rule you already tried, but replace in with in_array like so:

['payment_method' => 'required|array|in_array:american_express,cash_on_delivery,paypal,paypal_credit_card,visa_master_card']

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.