PHP code example of browner12 / validation

1. Go to this page and download the library: Download browner12/validation 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/ */

    

browner12 / validation example snippets

 php
'providers' => [
    browner12\validation\ValidationServiceProvider::class,
];
 sh
php artisan make:validator UserValidator
 php
namespace App\Services;

use App\Validation\ProductValidator;
use browner12\validation\ValidationException;

class ProductService
{
    /**
     * constructor
     *
     * @param \App\Validation\ProductValidator $validator
     */
    public function __construct(ProductValidator $validator)
    {
        $this->validator = $validator;
    }

    /**
     * store product
     *
     * @param array $input
     * @throws \browner12\validation\ValidationException
     */
    public function store(array $input)
    {
        if ($this->validator->isValid($input, 'store')) {
    
            //data is good, save to storage
            return true;
        }
    
        throw new ValidationException('Storing a product failed.', $this->validator->getErrors());
    }
}
 php
use App\Services\ProductService;
use browner12\validation\ValidationException;

class ProductController
{
    /**
     * constructor
     */
    public function __construct(ProductService $service)
    {
        $this->service = $service;
    }

    /**
     * store
     */
    public function store()
    {
        try {
        
            $data = [
                'name'  => $_POST['name'],
                'price' => $_POST['price'],
            ];
        
            $this->service->store($data);
        }
        
        catch (ValidationException $e){
        
            //handle the exception
        }
    }
}