All Projects → awurth → Slimvalidation

awurth / Slimvalidation

Licence: mit
A validator for PHP with Respect/Validation

Projects that are alternatives of or similar to Slimvalidation

Vs Validation
Common input and integrity validation routines for Visual Studio and other applications
Stars: ✭ 48 (-22.58%)
Mutual labels:  validation
Validate
This package provides a framework for writing validations for Go applications.
Stars: ✭ 57 (-8.06%)
Mutual labels:  validation
Codice Fiscale
A PHP library to calculate and check the italian tax code (codice fiscale).
Stars: ✭ 57 (-8.06%)
Mutual labels:  validation
Schemas
All schemas used for validation that are shared between our projects
Stars: ✭ 51 (-17.74%)
Mutual labels:  validation
Fmbbcodebundle
🔠 BBCode bundle for Symfony projects
Stars: ✭ 56 (-9.68%)
Mutual labels:  twig-extension
Awesomevalidation
Android validation library which helps developer boil down the tedious work to three easy steps.
Stars: ✭ 1,093 (+1662.9%)
Mutual labels:  validation
Celebrate
A joi validation middleware for Express.
Stars: ✭ 1,041 (+1579.03%)
Mutual labels:  validation
Is
Micro check library in Golang.
Stars: ✭ 61 (-1.61%)
Mutual labels:  validation
Inky Extension
[DEPRECATED] Inky email template engine support for Twig
Stars: ✭ 57 (-8.06%)
Mutual labels:  twig-extension
Lcformvalidation
Javascript based form validation library, third party library / framework agnostic.
Stars: ✭ 58 (-6.45%)
Mutual labels:  validation
Arg.js
🇦🇷 🛠 NPM library. Validation of Argentinian bank account numbers, IDs and phone numbers
Stars: ✭ 52 (-16.13%)
Mutual labels:  validation
Dry Validation
Validation library with type-safe schemas and rules
Stars: ✭ 1,087 (+1653.23%)
Mutual labels:  validation
Bottyclient
A slim Discord client with many cool features including less network traffic which supports bot tokens, but user tokens theoretically work too. Tags: Discord Bot Client Token for Bot Botting Download English
Stars: ✭ 58 (-6.45%)
Mutual labels:  slim
Elliot
Comprehensive and Rigorous Framework for Reproducible Recommender Systems Evaluation
Stars: ✭ 49 (-20.97%)
Mutual labels:  slim
Rest Hapi
🚀 A RESTful API generator for Node.js
Stars: ✭ 1,102 (+1677.42%)
Mutual labels:  validation
Laravel Smart
Automatic Migrations, Validation and More
Stars: ✭ 48 (-22.58%)
Mutual labels:  validation
Ng Bootstrap Form Validation
An Angular Module for easy data driven (reactive) form validation
Stars: ✭ 57 (-8.06%)
Mutual labels:  validation
Fhir.js
Node.JS library for serializing/deserializing FHIR resources between JS/JSON and XML using various node.js XML libraries
Stars: ✭ 61 (-1.61%)
Mutual labels:  validation
Govalid
Data validation library for golang. [MIGRATING TO NEW ADDRESS]
Stars: ✭ 59 (-4.84%)
Mutual labels:  validation
Io Ts Reporters
Error reporters for io-ts
Stars: ✭ 58 (-6.45%)
Mutual labels:  validation

Slim Validation

SensioLabsInsight Scrutinizer Code Quality Build Status Latest Stable Version Total Downloads License

A validator for PHP, using Respect Validation (Requires PHP 7+)

This project was originally designed to be used with the Micro-Framework "Slim", but can now be used with any psr/http-message compliant framework, or any other PHP project if you don't need request parameters validation.

Installation

$ composer require awurth/slim-validation

Configuration

To initialize the validator, create a new instance of Awurth\SlimValidation\Validator

Validator::__construct([ bool $showValidationRules = true [, array $defaultMessages = [] ]])
$showValidationRules
  • If set to true, errors will be stored in an associative array with the validation rules names as the key
$errors = [
    'username' => [
        'length' => 'The username must have a length between 8 and 16',
        'alnum' => 'The username must contain only letters (a-z) and digits (0-9)'
    ]
];
  • If set to false, errors will be stored in an array of strings
$errors = [
    'username' => [
        'The username must have a length between 8 and 16',
        'The username must contain only letters (a-z) and digits (0-9)'
    ]
];
$defaultMessages

An array of messages to overwrite the default Respect Validation messages

$defaultMessages = [
    'length' => 'This field must have a length between {{minValue}} and {{maxValue}} characters',
    'notBlank' => 'This field is required'
];

Add the validator as a service

You can add the validator to the app container to access it easily through your application

$container['validator'] = function () {
    return new Awurth\SlimValidation\Validator();
};

Usage

use Respect\Validation\Validator as V;

// The validate method returns the validator instance
$validator = $container->validator->validate($request, [
    'get_or_post_parameter_name' => V::length(6, 25)->alnum('_')->noWhitespace(),
    // ...
]);

if ($validator->isValid()) {
    // Do something...
} else {
    $errors = $validator->getErrors();
}

Validation methods

Request parameters validation

$_POST = [
    'username' => 'awurth',
    'password' => 'my_password'
];
/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 */

$validator->request($request, [
    'username' => V::notBlank(),
    'password' => V::length(8)
]);

Object properties validation

class ObjectToValidate {
    private $privateProperty;
    protected $protectedProperty;
    public $pulicProperty;
    
    // ...
}
/**
 * @var object $object
 */

$validator->object($object, [
    'privateProperty' => V::notBlank(),
    'protectedProperty' => V::notBlank(),
    'publicProperty' => V::notBlank()
]);

If a property does not exist, the tested value will be null

Array validation

$arrayToValidate = [
    'key_1' => 'value_1',
    'key_2' => 'value_2'
];
/**
 * @var array $arrayToValidate
 */

$validator->array($arrayToValidate, [
    'key_1' => V::notBlank(),
    'key_2' => V::notBlank()
]);

Single value validation

$validator->value('12345', V::numeric(), 'secret_code');

The validate() method

/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 */

$validator->validate($request, [
    'param' => V::notBlank()
]);

/**
 * @var object $object
 */

$validator->validate($object, [
    'property' => V::notBlank()
]);

/**
 * @var array $array
 */

$validator->array($array, [
    'key' => V::notBlank()
]);

$secretCode = '12345';
$validator->validate($secretCode, [
    'rules' => V::numeric(),
    'key' => 'secret_code'
]);

Error groups

$user = [
    'username' => 'awurth',
    'password' => 'my_password'
];

$address = [
    'street' => '...',
    'city' => '...',
    'country' => '...'
];

$validator->validate($user, [
    // ...
], 'user');

$validator->validate($address, [
    // ...
], 'address');
$validator->getErrors();

// Will return:
[
    'user' => [
        'username' => [
            // Errors...
        ]
    ],
    'address' => [
        'street' => [
            // Errors...
        ]
    ]
]

Custom messages

Slim Validation allows you to set custom messages for validation errors. There are 4 types of custom messages

Default rules messages

The ones defined in the Validator constructor.

Global rules messages

Messages that overwrite Respect Validation and default rules messages when calling the validate method.

$container->validator->validate($request, [
    'get_or_post_parameter_name' => V::length(6, 25)->alnum('_')->noWhitespace(),
    // ...
], null, [
    'length' => 'Custom message',
    'alnum' => 'Custom message',
    // ...
]);

Individual rules messages

Messages for a single request parameter. Overwrites all above messages.

$container->validator->validate($request, [
    'get_or_post_parameter_name' => [
        'rules' => V::length(6, 25)->alnum('_')->noWhitespace(),
        'messages' => [
            'length' => 'Custom message',
            'alnum' => 'Custom message',
            // ...
        ]
    ],
    // ...
]);

Single parameter messages

Defines a single error message for a request parameter, ignoring the validation rules. Overwrites all messages.

$container->validator->validate($request, [
    'get_or_post_parameter_name' => [
        'rules' => V::length(6, 25)->alnum('_')->noWhitespace(),
        'message' => 'This field must have a length between 6 and 25 characters and contain only letters and digits'
    ],
    // ...
]);

Twig extension

This package comes with a Twig extension to display error messages and submitted values in your Twig templates. You can skip this step if you don't want to use it.

To use the extension, you must install twig first

$ composer require slim/twig-view

Configuration

$container['view'] = function ($container) {
    // Twig configuration
    $view = new Slim\Views\Twig(...);
    // ...

    // Add the validator extension
    $view->addExtension(
        new Awurth\SlimValidation\ValidatorExtension($container['validator'])
    );

    return $view;
};

Functions

{# Use has_errors() function to know if a form contains errors #}
{{ has_errors() }}

{# Use has_error() function to know if a request parameter is invalid #}
{{ has_error('param') }}

{# Use error() function to get the first error of a parameter #}
{{ error('param') }}

{# Use errors() function to get all errors #}
{{ errors() }}

{# Use errors() function with the name of a parameter to get all errors of a parameter #}
{{ errors('param') }}

{# Use val() function to get the value of a parameter #}
{{ val('param') }}

Example

AuthController.php
public function register(Request $request, Response $response)
{
    if ($request->isPost()) {
        $this->validator->validate($request, [
            'username' => V::length(6, 25)->alnum('_')->noWhitespace(),
            'email' => V::notBlank()->email(),
            'password' => [
                'rules' => v::length(6, 25),
                'messages' => [
                    'length' => 'This field must have a length between {{minValue}} and {{maxValue}} characters'
                ]
            ],
            'confirm_password' => [
                'rules' => v::equals($request->getParam('password')),
                'messages' => [
                    'equals' => 'The password confirmation must be equal to the password'
                ]
            ]
        ]);
        
        if ($this->validator->isValid()) {
            // Register user in database
            
            return $response->withRedirect('url');
        }
    }
    
    return $this->view->render($response, 'register.twig');
}
register.twig
<form action="url" method="POST">
    <input type="text" name="username" value="{{ val('username') }}">
    {% if has_error('username') %}<span>{{ error('username') }}</span>{% endif %}
    
    <input type="text" name="email" value="{{ val('email') }}">
    {% if has_error('email') %}<span>{{ error('email') }}</span>{% endif %}
    
    <input type="text" name="password">
    {% if has_error('password') %}<span>{{ error('password') }}</span>{% endif %}
    
    <input type="text" name="confirm_password">
    {% if has_error('confirm_password') %}<span>{{ error('confirm_password') }}</span>{% endif %}
</form>
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].