Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation: validate field only if another is present

I wanted to validate an 'account_id' only if 'needs_login' is present. I did this:

$rules = [
    'account_id' => ['required_with:needs_login','custom_validation']
];

But it doesn't work, because if needs_login field is not present but account_id has some value, then it tries to do the 'custom_validation'. I also tried to put the 'sometimes' parameter

$rules = [
    'account_id' => ['required_with:needs_login', 'sometimes', 'custom_validation']
];

but it didn't work.

Any ideas?

P.S.: Remember that I wanted to validate the account_id only if needs_login is present, not to check if account_id is present if needs_login does.

like image 512
dani24 Avatar asked Oct 13 '15 15:10

dani24


2 Answers

Have you tried required_if?

$rules = [
    'account_id' => ['required_if:needs_login,1']
];
like image 103
IllegalPigeon Avatar answered Oct 30 '22 16:10

IllegalPigeon


Something like this works for Laravel 5 if you are going the 'sometimes' route. Perhaps you can adapt for L4? Looks like it's the same in the Docs.

$validation = Validator::make($formData, [
    'some_form_item' => 'rule_1|rule_2'
]
$validation->sometimes('account_id', 'required', function($input){
    return $input->needs_login == true;
});
like image 29
DonnaJo Avatar answered Oct 30 '22 14:10

DonnaJo