PHP code example of balsing / rock-validate

1. Go to this page and download the library: Download balsing/rock-validate library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

balsing / rock-validate example snippets


use rock\validate\Validate;

// Validation length from 10 to 20 characters inclusive + regexp pattern
$v = Validate::length(10, 20, true)->regex('/^[a-z]+$/i');
$v->validate('O’Reilly'); // output: false

$v->getErrors();
/*
output:

[
  'length' => 'value must have a length between 10 and 20',
  'regex' => 'value contains invalid characters'
]
*/

$v->getFirstError();
// output: value must have a length between 10 and 20

use rock\validate\Validate;

$v = Validate::length(10, 20, true)
            ->regex('/^[a-z]+$/i')
            ->setPlaceholders(['name' => 'username']);
$v->validate('O’Reilly'); // output: false

$v->getErrors();
/*
output:

[
  'length' => 'username must have a length between 10 and 20',
  'regex' => 'username contains invalid characters',
]
*/

use rock\validate\Validate;

$v = Validate::length(10, 20, true)->regex('/^[a-z]+$/i')->setLocale('ru');
$v->validate('O’Reilly'); // output: false

$v->getErrors();
/*
output:

[
  'length' => 'значение должно иметь длину в диапазоне от 10 до 20',
  'regex' => 'значение содержит неверные символы',
]
*/

use rock\validate\Validate;

$input = [
    'username' => 'O’Reilly',
    'email' => 'o-reilly@site'
];
$attributes = [
  'username' => Validate::ail()
];

$v = Validate::attributes($attributes);
$v->validate($input); // output false

$v->getErrors();
/*
output:

[
  'username' => [
    'length' => 'username must have a length between 10 and 20',
    'regex' => 'username contains invalid characters',
  ],
  'email' => [
    'email' => 'email must be valid email',
  ]
]
*/

$attribute = 'email';
$v->getFirstError($attribute);
// output: email must be valid