Skip to content

Latest commit

 

History

History
executable file
·
64 lines (41 loc) · 1.78 KB

3.2 - Execute validation.md

File metadata and controls

executable file
·
64 lines (41 loc) · 1.78 KB

3.2 - Execute validation

Execute, fails and passes

The validator comes with an arsenal of built-in validation rules. To execute validation, you may use the execute(), fails() or passes() method.

$validator->field('username')->lengthMin(5)->lengthMax(20);

//Returns bool false/true
$passes = $validator->execute(); 

if($validator->passes()) {
    //Validation success
}

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

The validator will only run once to avoid i.e. multiple database lookups when executing the execute(), fails() or passes() methods.

Re-validate

By default, the validator caches the validation result. So if you run the same validator again, the validator won't run all the rules, middleware, etc. It will directly return the result of the previous run.

To run the validator with all rules, middleware, etc. again, you can use the revalidate() method:

use KrisKuiper\Validator\Validator;

$executed = 0;
$validator = new Validator(['username' => 'Morris']);

$customRule = function () use (&$executed) {

    $executed++;
    return true;
};

$validator->custom('myCustomRule', $customRule);
$validator->field('username')->custom('myCustomRule');

//Execute validation
$validator->execute();
var_dump($executed); //1

//Executing the validation again will have the same result
$validator->execute();
var_dump($executed); //Still 1

//Rerun the validation with all rules, middleware, etc.
$validator->revalidate();
var_dump($executed); //Is now 2

Go to the previous section.

Go to the next section.