Skip to content

Latest commit

 

History

History
executable file
·
75 lines (49 loc) · 1.87 KB

3.1 - Adding fields for validation.md

File metadata and controls

executable file
·
75 lines (49 loc) · 1.87 KB

3.1 - Adding fields for validation

By using the field() method, you can add one or more field names for validation.

Example 1:

Add one or combine multiple fields to attach rules and more:

use KrisKuiper\Validator\Validator;

$input = ['username' => '', 'password' => '', 'email' =>> ''];

$validator = new Validator($input);

//You can add a single field name
$validator->field('username')->required();

//Or add multiple field names
$validator->field('username', 'password', 'email')->required();

Example 2:

You can also use wildcards:

$data = [
    'programmers' => [
        'name' => 'Morris',
        'email' => 'morris@domain.com'
    ],
    'developers' => [
        'name' => 'Smith',
        'email' => 'smith@domain.com'
    ]
];

$validator = new Validator($data);

//Select every email field within an array using wildcards and attach different rules
$validator->field('*.email')->required()->email();

Validating arrays

You can also validate an array of fields. You can validate all the single elements in an array by using a * character. Although it's not mandatory, but recommended to validate the array as an array as well for proper error messages.

Example

$input = [
    'emails' => [
        'john@example.com', 
        'smith@example.com',
        'morris@example.com',
    ]
];

$validator = new Validator($input);

$validator->field('email')->isArray(); //Check if the value is in array (recommended)
$validator->field('email.*')->email(); //Each value should be a valid email address

Note: Rules are executed in the order they are defined.


Go to the previous section.

Go to the next section.