All Projects → illuminatech → Validation Composite

illuminatech / Validation Composite

Licence: other
Allows uniting of several validation rules into single one for easy re-usage

Projects that are alternatives of or similar to Validation Composite

Validation
The power of Respect Validation on Laravel
Stars: ✭ 188 (+18.24%)
Mutual labels:  validation, validator, laravel
Validation
🔒 Laravel farsi/persian validation
Stars: ✭ 142 (-10.69%)
Mutual labels:  validation, validator, laravel
Credit Card
Credit Card Validation
Stars: ✭ 150 (-5.66%)
Mutual labels:  validation, validator, laravel
Laravel Zip Validator
Laravel ZIP file content validator
Stars: ✭ 120 (-24.53%)
Mutual labels:  validation, validator, laravel
Laravel Multistep Forms
Responsable Multistep Form Builder for Laravel
Stars: ✭ 76 (-52.2%)
Mutual labels:  validation, laravel
Form Object
Form object to use with Vue components for sending data to a Laravel application using axios.
Stars: ✭ 73 (-54.09%)
Mutual labels:  validation, laravel
Validatorjs
A data validation library in JavaScript for the browser and Node.js, inspired by Laravel's Validator.
Stars: ✭ 1,534 (+864.78%)
Mutual labels:  validation, laravel
Awesome Python Models
A curated list of awesome Python libraries, which implement models, schemas, serializers/deserializers, ODM's/ORM's, Active Records or similar patterns.
Stars: ✭ 124 (-22.01%)
Mutual labels:  validation, validator
Inspector
A tiny class validation library.
Stars: ✭ 64 (-59.75%)
Mutual labels:  validation, validator
Validator
A tool to validate text inside TextInputLayout
Stars: ✭ 117 (-26.42%)
Mutual labels:  validation, validator
Laravel Phone
Phone number functionality for Laravel
Stars: ✭ 1,806 (+1035.85%)
Mutual labels:  validation, laravel
Aura.filter
Validate and sanitize arrays and objects.
Stars: ✭ 134 (-15.72%)
Mutual labels:  validation, validator
Unicorn
Unicorn - W3C's Unified Validator
Stars: ✭ 70 (-55.97%)
Mutual labels:  validation, validator
Schemasafe
A reasonably safe JSON Schema validator with draft-04/06/07/2019-09 support.
Stars: ✭ 67 (-57.86%)
Mutual labels:  validation, validator
Ngx Dynamic Form Builder
FormBuilder + class-transformer + class-validator = dynamic form group builder for Angular10+
Stars: ✭ 93 (-41.51%)
Mutual labels:  validation, validator
Vee Validate
✅ Form Validation for Vue.js
Stars: ✭ 8,820 (+5447.17%)
Mutual labels:  validation, validator
Property Validator
✅ Easy property validation for JavaScript, Node and Express.
Stars: ✭ 153 (-3.77%)
Mutual labels:  validation, validator
Laravel Smart
Automatic Migrations, Validation and More
Stars: ✭ 48 (-69.81%)
Mutual labels:  validation, laravel
Is
Micro check library in Golang.
Stars: ✭ 61 (-61.64%)
Mutual labels:  validation, validator
Apvalidators
Codeless solution for form validation in iOS!
Stars: ✭ 130 (-18.24%)
Mutual labels:  validation, validator

Laravel Composite Validation


This extension allows uniting several Laravel validation rules into a single one for easy re-usage.

For license information check the LICENSE-file.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist illuminatech/validation-composite

or add

"illuminatech/validation-composite": "*"

to the require section of your composer.json.

Usage

The same sequence of the validation rules may repeat over the application many times. For example: you may have a set of restrictions related to the user's password, like it should be at least 8 symbols long, but shorter then 200 to fit the database field reserved for its storage. Your program may also allow user to upload an image to be his avatar, but in order to make it safe, you should validate uploaded file mime type and size. Thus validation for the user profile form may looks like following:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    public function update(Request $request)
    {
        $validatedData = $request->validate([
            'password' => ['required', 'string', 'min:8', 'max:200'],
            'avatar' => ['required', 'file', 'mimes:png,jpg,jpeg', 'max:1024'],
            // ...
        ]);
        
        // ...
    }
}

The problem is: validation for user's password or avatar may appear in several different places. For example: password can be setup at sign-up process, during password reset and so on. You may also have a separated administration panel, which allows system administrator to adjust existing user's record or create a new one. Thus you will have to duplicate all these validation rules many times throughout your project source code. In case requirements change, for example: we decide that password length should be at least 10 symbols instead of 8, or disallow '*.png' files from avatar - you'll have to manually changes validation rules at all those places.

This extension allows uniting several validation rules into a single one for easy re-usage. For the example above you should create 2 separated validation rule classes extending Illuminatech\Validation\Composite\CompositeRule:

<?php

namespace App\Rules;

use Illuminatech\Validation\Composite\CompositeRule;

class PasswordRule extends CompositeRule
{
    protected function rules(): array
    {
        return ['string', 'min:8', 'max:200'];
    }
}

class AvatarRule extends CompositeRule
{
    protected function rules(): array
    {
        return ['file', 'mimes:png,jpg,jpeg', 'max:1024'];
    }
}

Here method rules() defines list of validation rules, which will be applied by defined rule internally. Now we can rewrite the form validation in following way:

<?php

namespace App\Http\Controllers;

use App\Rules\AvatarRule;
use App\Rules\PasswordRule;
use Illuminate\Http\Request;

class ProfileController extends Controller
{
    public function update(Request $request)
    {
        $validatedData = $request->validate([
            'password' => ['required', new PasswordRule],
            'avatar' => ['required', new AvatarRule],
            // ...
        ]);
        
        // ...
    }
}

With such approach you can change validation for the 'password' and 'avatar' at the single place.

In case composite validation rule fails, validator instance will pick up an error message from the particular sub-rule. For example:

<?php

use App\Rules\PasswordRule;
use Illuminate\Support\Facades\Validator;

$validator = Validator::make(
    ['password' => 'short'],
    [
        'password' => ['required', new PasswordRule],
    ]
);

if ($validator->fails()) {
    echo $validator->errors()->first('password'); // outputs 'The password must be at least 8 characters.'
}

Note: do not use rules like 'sometimes', 'required', 'required_with', 'required_without' and so on in the composite rule. These are processed at the different validation level and thus will have no effect or may behave unexpectedly.

You may define composite validation rules using validation factory extensions feature. For such case you may use Illuminatech\Validation\Composite\DynamicCompositeRule. For example:

<?php

namespace App\Providers;

use Illuminate\Contracts\Validation\Factory;
use Illuminate\Support\ServiceProvider;
use Illuminatech\Validation\Composite\DynamicCompositeRule;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->extend('validator', function (Factory $validatorFactory) {
            $validatorFactory->extend('password', function ($attribute, $value) {
                return (new DynamicCompositeRule(['string', 'min:8', 'max:200']))->passes($attribute, $value);
            });
            
            $validatorFactory->extend('avatar', function ($attribute, $value) {
                return (new DynamicCompositeRule(['file', 'mimes:png,jpg,jpeg', 'max:1024']))->passes($attribute, $value);
            });

            return $validatorFactory;
        });
        
        // ...
    }
}

Note that with such approach automatic pick up of the validation error message becomes impossible, and you will have to setup it explicitly in language files.

You may specify custom error messages per each validation rule used in the composite one, overriding messages() method. For example:

<?php

namespace App\Rules;

use Illuminatech\Validation\Composite\CompositeRule;

class PasswordRule extends CompositeRule
{
    protected function rules(): array
    {
        return ['string', 'min:8', 'max:200'];
    }

    protected function messages(): array
    {
        return [
            'string' => 'Only string is allowed.',
            'min' => ':attribute is too short.',
            'max' => ':attribute is too long.',
        ];
    }
}
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].