K
K
koida_yuri2016-11-30 12:32:48
Laravel
koida_yuri, 2016-11-30 12:32:48

How to do multi-validation in Laravel?

There is such a task:
term_installments - If first_payment is not 100 then between:0,12
term_installments - If resource_id = 154 then between:0,60
Then you need to specify 2 bitwins in one check.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2016-11-30
@koida_yuri

AppServiceProvider (although I have a separate ValidatorServiceProvider for such things) in the boot method.
As far as I understand, you must first check the resource_id, and then first_payment.
The idea is clear, the implementation is up to you.

\Validator::extend('your_rule_name', function ($attr, $value, $params, \Illuminate\Validation\Validator $validator) {
    // request data
    $data = $validator->getData();
    
    if (array_get($data, 'resource_id') === 154) {
        return $value >= 0 && $value <= 60;
    }
    
    if (array_get($data, 'first_payment') !== 100) {
        return $value >= 0 && $value <= 12;
    }
    
    return false;
});

O
Oleg, 2016-11-30
@ollisso

In order not to create a rule every time, you can make it easier:

$validator = Validator::make(...);

$validator->after(function ($validator) {
    if ($this->somethingElseIsInvalid()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    //
}

Those. after the basic rules have been checked, check and something else :)
The code can be any there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question