Skip to content

Latest commit

 

History

History
executable file
·
71 lines (50 loc) · 2.21 KB

6.1 - Conditionally adding rules.md

File metadata and controls

executable file
·
71 lines (50 loc) · 2.21 KB

6.1 - Conditionally adding rules

Sometimes you may wish to add validation rules based on more complex conditional logic. For example, you may want to validate the incoming data by checking if the amount of products is higher than 99, then the reason of purchase should be filled in.

This can be achieved by using the if() method:

use KrisKuiper\Validator\Validator;
use KrisKuiper\Validator\Blueprint\Events\Event;

$data = [
    'amount' => 100,
    'reason' => null
];

$validator = new Validator($data);
$validator
    ->field('reason')
    ->if(function(Event $event) {
        
        //Retrieve the value of the amount field
        return $event->getValue('amount') > 99
        
        //Or use the built-in validator
        return $event->field('amount')->min(99)->isValid();
    })
    ->required()
    ->lengthMax(2000);

$validator->execute());

In this example, the validation will fail because the amount is higher than 99, so the reason field is required. If the amount was below 100, validation would have pass.

Using multiple conditions

Although the last rule isString, in the example below, requires the provided data to be a string and the provided age field is an interger number (25), the validation still succeeds. This is because the last if rule returns false, so the isString rule is not executed.

use KrisKuiper\Validator\Validator;
use KrisKuiper\Validator\Blueprint\Events\Event;

$data = ['age' => 25];
$validator = new Validator($data);

$validator
    ->field('age')
    ->if(function () {
        return true;
    })
    ->min(10) //Should be at least 10
    ->if(function () {
        return true;
    })
    ->max(30) //Should be a maximum of 30
    ->if(function () {
        return false; //This will prevent executing the next rule
    })
    ->isString(); //This rule won't be executed

$validator->execute(); //Returns true

Go to the previous section.

Go to the next section.