saroj-pant/validation

Validation package

v1.0.0 2016-07-18 15:51 UTC

This package is auto-updated.

Last update: 2024-12-13 10:20:02 UTC


README

How does this work?

Step 1. Create an instance

$validator = new SarojPant\Validation\Validator();

Step 2. Call the validate() method

$validator->validate($data, $rules, $validationMessages);

Step 3. Check validation results

if ($validator->passed() { // Do something }
if ($validator->failed() { // Do something }
var_dump($validator->getErrors();
var_dump($validator->getErrors('first_name');
echo $validator->getFirstError();
echo $validator->getFirstError('first_name');
if ($validator->hasError()) { // Do something }
if ($validator->hasError('name')) { // Do something }

Validation rules

The validate method expects an array of field names with rules.

A rule is just a string that will need at least a valid rule name.

$rules = ['name' => 'required'];

Arguments can be passed to a rule using a colon (:).

$rules = ['name' => 'minLength:6'];

Multiple rules can be applied to a field by using pipe(|).

$rules = ['name' => 'required|minLength:6]';

Available rules

required

Usage:

// $data = (array) ...
$rules = ['name' => 'required'];
$validationMessages = ['name' => 'Name is required.'];
$validator->validate($rules, $data, $validationMessages);

equals

Usage:

$rules = ['confirm_password' => 'equals|password'];
$validationMessages = ['confirm_password.equals' => 'Password did not match.'];
$validator->validate($rules, $data, $validationMessages);

equalsBooleanTrue

Usage:

$rules = ['i_agree' => 'equalsBooleanTrue'];

equalsBooleanFalse

Usage:

$rules = ['i_agree' => 'equalsBooleanFalse'];

email

Usage:

$rules = ['username' => 'email'];

int

Usage:

$rules = ['age' => 'int'];

unsigned

Usage:

$rules = ['age' => 'unsigned'];

min

Usage:

$rules = ['age' => 'min:21'];

max

Usage:

$rules = ['age' => 'max:55'];

minLength

Usage:

$rules = ['comment' => 'minLength: 80'];

maxLength

Usage:

$rules = ['username' => 'maxLength: 20'];

inCsv

$rules = ['name' => 'inCsv: Greg, Anne, Lucy, Sophie'];

Simple contact form example

/** @var Request $request */
$data = $request->request->all();
$rules = [
    'name' => 'required',
    'email' => 'email',
    'message' => 'required|minLength:30'
];
$validationMessages = [
    'name' => 'Name is required.',
    'email' => 'Invalid Email.',
    'message.required' = 'Message is required.',
    'message.minLength' = 'Message should be at least 30 characters.'
];

$validator = new \SarojPant\Validation\Validation();
$validator->validate($data, $rules, $validationMessages);

if ($validator->passed()) {
    echo 'Thank you for your message.';
} else {
   if ($validator->hasError('name') {
       echo '<span class="error">' . $validator->getFirstError('name') . '</span>';
   }
   
   // ..
}



Test

Run phpunit in the SarojPant\Validation folder.