Laravel Validation Service

Overview

Laravel Validation Service

Total Downloads Latest Stable Version Latest Unstable Version License

Installation

Add "prettus/laravel-repository": "1.1.*" to composer.json

"prettus/laravel-validation": "1.1.*"

Create a validator

The Validator contains rules for adding, editing.

Prettus\Validator\Contracts\ValidatorInterface::RULE_CREATE
Prettus\Validator\Contracts\ValidatorInterface::RULE_UPDATE

In the example below, we define some rules for both creation and edition

use \Prettus\Validator\LaravelValidator;

class PostValidator extends LaravelValidator {

    protected $rules = [
        'title' => 'required',
        'text'  => 'min:3',
        'author'=> 'required'
    ];

}

To define specific rules, proceed as shown below:

use \Prettus\Validator\LaravelValidator;

class PostValidator extends LaravelValidator {

    protected $rules = [
        ValidatorInterface::RULE_CREATE => [
            'title' => 'required',
            'text'  => 'min:3',
            'author'=> 'required'
        ],
        ValidatorInterface::RULE_UPDATE => [
            'title' => 'required'
        ]
   ];

}

Custom Error Messages

You may use custom error messages for validation instead of the defaults

protected $messages = [
    'required' => 'The :attribute field is required.',
];

Or, you may wish to specify a custom error messages only for a specific field.

protected $messages = [
    'email.required' => 'We need to know your e-mail address!',
];

Custom Attributes

You too may use custom name attributes

protected $attributes = [
    'email' => 'E-mail',
    'obs' => 'Observation',
];

Using the Validator

use \Prettus\Validator\Exceptions\ValidatorException;

class PostsController extends BaseController {

    /**
     * @var PostRepository
     */
    protected $repository;
    
    /**
     * @var PostValidator
     */
    protected $validator;

    public function __construct(PostRepository $repository, PostValidator $validator){
        $this->repository = $repository;
        $this->validator  = $validator;
    }
   
    public function store()
    {

        try {

            $this->validator->with( Input::all() )->passesOrFail();
            
            // OR $this->validator->with( Input::all() )->passesOrFail( ValidatorInterface::RULE_CREATE );

            $post = $this->repository->create( Input::all() );

            return Response::json([
                'message'=>'Post created',
                'data'   =>$post->toArray()
            ]);

        } catch (ValidatorException $e) {

            return Response::json([
                'error'   =>true,
                'message' =>$e->getMessage()
            ]);

        }
    }

    public function update($id)
    {

        try{
            
            $this->validator->with( Input::all() )->passesOrFail( ValidatorInterface::RULE_UPDATE );
            
            $post = $this->repository->update( Input::all(), $id );

            return Response::json([
                'message'=>'Post created',
                'data'   =>$post->toArray()
            ]);

        }catch (ValidatorException $e){

            return Response::json([
                'error'   =>true,
                'message' =>$e->getMessage()
            ]);

        }

    }
}

Author

Anderson Andrade - [email protected]

Credits

http://culttt.com/2014/01/13/advanced-validation-service-laravel-4/

Comments
  • Enviar ID no RULE_UPDATE

    Enviar ID no RULE_UPDATE

    Como faço para enviar o ID do meu objeto, para fazer a validação do mesmo?

    Algo do tipo:

    class TagValidator extends LaravelValidator
    {
        protected $rules = [
            ValidatorInterface::RULE_CREATE => [
                'name' => 'required|min:3|max:50',
            ],
            ValidatorInterface::RULE_UPDATE => [
                'id'   => 'required|exists:tag',
                'name' => 'required|min:3|max:50|unique:tag,name,' . $id,
            ]
        ];
    }
    
    opened by felipeminello 35
  • Validating unique

    Validating unique

    This is my validation class, how does the validator automatically takes the id when updating an existing entity ? Do i need to pass the id? or just leave it. None seems to be working correctly.

    class StudentValidator extends LaravelValidator {
    
        protected $rules = [
            'username' => 'required|unique:users,username,$id', // <--here
            'admission_date' => 'required|date',
            'first_name' => 'required',
            'last_name' => 'required'
        ];
    
    }
    
    opened by astroanu 13
  • Create an specific rule

    Create an specific rule

    Right now, I'm using this package with l5-repositories. I need to create a custom method in my repository and request validation to it.

    My CountryValidator seems like

    protected $rules = [
        ValidatorInterface::RULE_CREATE => [
          'iso'=>'required|string|unique:countries|max:3',
          'title'=>'required|string|unique:states|max:50'
        ],
        ValidatorInterface::RULE_UPDATE => [
          'iso'=> 'string|max:3|unique:countries,iso',
          'title'=>'string|max:50|unique:countries,title',
        ],
        'ADD_STATES' => [
          'states' => 'required|array',
          'states.*.title' => 'required|string|max:50'
        ]
      ];
    

    And my controller looks like:

    public function addStates(CountryUpdateRequest $request, $id)
      {
        try {
          $this->validator->with($request->all())->passesOrFail(CountryValidator::ADD_STATES);
    
          $country = $this->repository->addStates($request->all(), $id);
    
          $response = [
            'message' => 'States added to the country.',
            'data'    => $country->toArray(),
          ];
    
        } catch (Exception $e) {
    
          if ($request->wantsJson()) {
    
            return response()->json([
              'error'   => true,
              'message' => $e->getMessageBag()
            ]);
          }
        }
    

    But when I send a invalid request (i.e. {}) the validator doesn't works and throws a passOrFail exception. What can it be?

    opened by golinmarq 3
  • Compatibility with l5-repository

    Compatibility with l5-repository

    I can not use laravel-validator in version dev-master and L5-repository at the same time.

    "Prettus / laravel-validation": "1.1. *"

    It would be possible to launch a release with the changes of custom messages (commit 64f66f70d1f291d30370cd255b1c75ac53351d80) ?

    Thanks

    opened by zepaduajr 2
  • Condicionais nas regras

    Condicionais nas regras

    Estou criando um projeto onde preciso cadastrar um cliente, e o cliente pode ser pessoa física ou jurídica, e preciso validar o campo cpf como required se ele for pessoa fisica e o campo cnpj se for pessoa juridica, existe alguma maneira de criar uma condição de por exemplo:

    chame as $rules X se for pessoa juridica e chame as $rules Y se for pessoa fisica

    opened by mja-maia 1
  • How to validate nested json and array?

    How to validate nested json and array?

    I tried this but did not work.

      ValidatorInterface::RULE_CREATE => [
            'title'  => 'required|min:3',
            'extras.type' => 'required',
        ],
    
    opened by DesmondPang 1
  • Bind LaravelValidator to controller method

    Bind LaravelValidator to controller method

    Does anybody know how to bind LaravelValidator to controller method like laravel FormRequest? For example,

    class PostValidator extends LaravelValidator {
        protected $rules = [
            'someMethod' => [
                'someField' => 'required',
            ],
        ];
    }
    
    class PostController
    {
        public function someMethod(PostValidator $validator)
        {
            // validation has been done to this point
            // if validation fail it must throw ValidationException
        }
    }
    
    opened by melihovv 0
  • Fixes: Undefined offset 1 in Lumen

    Fixes: Undefined offset 1 in Lumen

    In Lumen, when trying to update a model I got:

    ErrorException in AbstractValidator.php line 171:
    Undefined offset: 1
    

    I tried to see if updating worked in Laravel 5, it did, without any problems. I then researched some more on the undefined issue. This is what led me to the solution: https://www.daniweb.com/web-development/php/threads/452877/-how-to-prevent-undefined-offset-1-

    I can confirm that my fix works in both Laravel 5 and Lumen. I hope you accept this pull request.

    Thanks.

    opened by henninghorn 0
  • Fix/validate update custom rule

    Fix/validate update custom rule

    When using custom validation rules AbstractValidator::parserValidationRules() fails because it is expecting all rules to be defined as a string. Laravel Validator allows you to define custom rules as Rule objects. In this case AbstractValidator::parserValidationRules() should pass them through as-is.

    opened by kevin-foster-uk 0
  • Update rules

    Update rules

    How to pass the reference id for update rules. I know we can pass it by setId but how to set that as reference inside update rules. For example 'slug' => "required|string|unique:restaurateurs,slug,{$id}",

    opened by ahmadsaeed12 0
  • Support setAttributeNames to allow localisation

    Support setAttributeNames to allow localisation

    Laravel's default validation provides a method setAttributeNames to allow overwriting attribute names that come with the request, as in most cases they aren't meant for end users to understand, and the maintain the same names even when the locale changes.

    opened by photonite 0
Releases(1.4.0)
Owner
Anderson Andrade
AWS Solutions Architect
Anderson Andrade
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
高性能的验证器组件(Validation),适用于 Hyperf 或 Laravel 框架,可获得数百倍的性能提升

验证器 简介 兼容 Hyperf/Laravel Validation 规则 部分场景可获得约 500 倍性能提升 验证器可多次复用不同数据,无状态设计 规则可全局复用 智能合并验证规则 安装 环境要求 PHP >= 8.0 mbstring 扩展 ctype 扩展 安装命令 composer re

KK集团 80 Dec 9, 2022
Extension for the Laravel validation class

Intervention Validation Intervention Validation is an extension library for Laravel's own validation system. The package adds rules to validate data l

null 370 Dec 30, 2022
Extra validation rules for dealing with images in Laravel 5.

Image-Validator Extra validation rules for dealing with images in Laravel 5. NOTE: As of Laravel version 5.2, there are now built-in validation rules

Colin Viebrock 223 Jun 16, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
File uploads with validation and storage strategies

Upload This component simplifies file validation and uploading. Usage Assume a file is uploaded with this HTML form: <form method="POST" enctype="mult

Brandon Savage 1.7k Dec 27, 2022
Valitron is a simple, elegant, stand-alone validation library with NO dependencies

Valitron: Easy Validation That Doesn't Suck Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron us

Vance Lucas 1.5k Dec 30, 2022
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

PHP Validate 一个简洁小巧且功能完善的php验证、过滤库。 简单方便,支持添加自定义验证器 支持前置验证检查, 自定义如何判断非空 支持将规则按场景进行分组设置。或者部分验证 支持在进行验证前对值使用过滤器进行净化过滤内置过滤器 支持在进行验证前置处理和后置处理独立验证处理 支持自定义每

Inhere 246 Jan 5, 2023
Abstracts HTTP request input handling, providing an easy interface for data hydration and validation

Linio Input Linio Input is yet another component of the Linio Framework. It aims to abstract HTTP request input handling, allowing a seamless integrat

Linio 41 Dec 12, 2021
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
Light and extendable schema validation library

Light PHP validation library For everyone who uses MongoDB or other NoSQL solution and cares about what client sends to his/her database and looking f

Alexander Serkin 43 Sep 28, 2022
One Line Validation, For CodeIgniter 4

One Line Validation (OLV) is a package made for CodeIgniter 4 to provide a fast and single line validation experience ideal for CDN and/or API services consuming the Validation System from CodeIgniter 4.

AJ Meireles 2 Sep 21, 2021
Validation rules for Money and Currency

money-validation-laravel Validation rules for Money and Currency Installation composer require brokeyourbike/money-validation-laravel Usage Package us

Ivan Stasiuk 1 Oct 25, 2021
laminas-password-validator provides a validator for character-set based input validation.

laminas-password-validator laminas-password-validator provides a validator for character-set based input validation. Installation composer require pra

null 1 Mar 8, 2022
An extensible validation library for your data with sane defaults.

Hird Hirds, also known as housecarls, was a gathering of hirdmen, who functioned as the king's personal guards during the viking age and the early mid

Asko Nõmm 13 Apr 23, 2022
FyreValidation is a free, open-source validation library for PHP.

FyreValidation FyreValidation is a free, validation library for PHP. Table Of Contents Installation Validators Rules Error Messages Installation Using

Elusive 0 Jan 15, 2022
Laravel quickly creates a verification code tool similar to Google verification code

laravel-gridCaptcha Laravel quickly creates a verification code tool similar to Google verification code laravel 快速创建一个类似于 Google 点图验证码的本地验证码扩展 介绍 lar

delete DB Flee 14 Mar 1, 2022
Custom Laravel Validator for combined unique indexes

unique_with Validator Rule For Laravel This package contains a variant of the validateUnique rule for Laravel, that allows for validation of multi-col

Felix Kiss 383 Oct 18, 2022
Laravel Validation Service

Laravel Validation Service Installation Add "prettus/laravel-repository": "1.1.*" to composer.json "prettus/laravel-validation": "1.1.*" Create a vali

Anderson Andrade 398 Nov 25, 2022
Email validation service in PHP

Email validation service Email validation service in PHP using Laravel 8. Validation features Domain Regular Expression Smtp Txt records Installing de

Pedro 1 Oct 30, 2021