PHPackages                             hnrazevedo/validator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. hnrazevedo/validator

ActiveLibrary

hnrazevedo/validator
====================

Validator is a simple data validation component.

v2.1.4(5y ago)0384MITPHPPHP &gt;=7.4

Since Aug 11Pushed 5y ago1 watchersCompare

[ Source](https://github.com/hnrazevedo/Validator)[ Packagist](https://packagist.org/packages/hnrazevedo/validator)[ RSS](/packages/hnrazevedo-validator/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (20)Used By (0)

Validator @HnrAzevedo
=====================

[](#validator-hnrazevedo)

[![Maintainer](https://camo.githubusercontent.com/635097b3bfe7b55e89a425855fb0567f79aea687d3f7176a187b388ed7c99d56/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6d61696e7461696e65722d40686e72617a657665646f2d626c75653f7374796c653d666c61742d737175617265)](https://github.com/hnrazevedo)[![Latest Version](https://camo.githubusercontent.com/44cd72a06f39697856f2375106bf7234e18518bdca6d2117fe9116ce80296f64/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f7461672f686e72617a657665646f2f76616c696461746f723f6c6162656c3d76657273696f6e267374796c653d666c61742d737175617265)](https://github.com/hnrazevedo/Validator/releases)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/f4a3772c671000fecafeda855c3c2fb40c485bc3dc9ce311b180d5e760164227/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f7175616c6974792f672f686e72617a657665646f2f76616c696461746f723f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/hnrazevedo/Validator/?branch=master)[![Build Status](https://camo.githubusercontent.com/9104dbca7105cefaf596d071f16fa422a8ffd83488a4603d940edf3f6f32b71a/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f6275696c642f672f686e72617a657665646f2f76616c696461746f723f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/hnrazevedo/Validator/build-status/master)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![PHP from Packagist](https://camo.githubusercontent.com/e5602b79afe85caa9ef030d014208fd0bdfedbfd8acb5e28b6efd30ec003d52b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f686e72617a657665646f2f76616c696461746f723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hnrazevedo/validator)[![Total Downloads](https://camo.githubusercontent.com/d07b57b48e6d429c230bc7f9ba425938cf32cc6a0a3a23abbf804cbf0aa40969/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686e72617a657665646f2f76616c696461746f723f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hnrazevedo/validator)

##### The Validator is a simple data validation component. It can be used statically with a controller or together as middleware. Its author is not a professional in the development area, just someone in the Technology area who is improving his knowledge.

[](#the-validator-is-a-simple-data-validation-component-it-can-be-used-statically-with-a-controller-or-together-as-middleware-its-author-is-not-a-professional-in-the-development-area-just-someone-in-the-technology-area-who-is-improving-his-knowledge)

O Validator é um simples componente de validação de dados. Ele pode ser usado de forma estática com algum controlador ou em conjunto como middleware. Seu autor não é profissional da área de desenvolvimento, apenas alguem da área de Tecnologia que está aperfeiçoando seus conhecimentos.

### Highlights

[](#highlights)

- Easy to set up (Fácil de configurar)
- Current validation rules (Regras de validação atuais)
- Follows standard PSR-15 (Segue padrão o PSR-15)
- Composer ready (Pronto para o composer)

Installation
------------

[](#installation)

Validator is available via Composer:

```
"hnrazevedo/validator": "^2.1"
```

or in at terminal

```
composer require hnrazevedo/validator
```

Documentation
-------------

[](#documentation)

##### For details on how to use the Validator, see the sample folder with details in the component directory

[](#for-details-on-how-to-use-the-validator-see-the-sample-folder-with-details-in-the-component-directory)

Para mais detalhes sobre como usar o Validator, veja a pasta de exemplos com detalhes no diretório do componente

### Validation rules

[](#validation-rules)

#### Available rules

[](#available-rules)

- minlength: integer
- maxlength: integer
- required: boolean
- equals: string
- type: string
- mincount: integer - For arrays values
- maxcount: integer - For arrays values
- filter: integer - See  for more details of the available filters
- regex: string

### Languages

[](#languages)

#### The system has been configured to support multiple languages, so make sure the desired language is in the languages folder and define it with the lang method before any procedure

[](#the-system-has-been-configured-to-support-multiple-languages-so-make-sure-the-desired-language-is-in-the-languages-folder-and-define-it-with-the-lang-method-before-any-procedure)

O sistema foi configurado para suportar vários idiomas, então verifique se o idioma desejado se encontra na pasta languages e defina-o com o método lang antes de qualquer procedimento

```
$valid = Validator::lang('pt_br')->namespace('App\\Rules')->execute($data);
```

NOTE
----

[](#note)

#### In case the field is an array, the rules will be tested in all its elements.

[](#in-case-the-field-is-an-array-the-rules-will-be-tested-in-all-its-elements)

Em caso do campo ser um array, as regras serão testadas em todos seus elementos.

#### The validation rules must be defined in the construction of the class object with the namespace denified in the Validator

[](#the-validation-rules-must-be-defined-in-the-construction-of-the-class-object-with-the-namespace-denified-in-the-validator)

As regras de validação devem ser definidas na construção do objeto da classe com o namespace denifida no Validator

```
namespace App\Rules;

use HnrAzevedo\Validator\Validator;
use HnrAzevedo\Validator\Rules;

Class User{

    public function __construct()
    {
        Validator::add($this, function(Rules $rules){
            $rules->action('login')
                  /*
                   * @property string $inputName
                   * @property array $rules
                   * @property string $textPlaceholder
                  */
                  ->field('email',['minlength'=>1,'filter'=>FILTER_VALIDATE_EMAIL,'required'=>true],'Email address')
                  ->field('password',['minlength'=>6,'maxlength'=>20,'required'=>true],'Password')
                  ->field('password2',['equals'=>'password','required'=>true],'Confirm password')
                  ->field('remember',['minlength'=>2,'maxlength'=>2,'required'=>false])
                  ->field('birth',['type'=>'date','required'=>true],'Date of birth')
                  ->field('phones',['mincount'=>2,'maxcount'=>3,'required'=>true,'minlength'=>8,'maxlength'=>9]);
            return $rules;
        });
        return $this;
    }

}
```

### Data format for validation

[](#data-format-for-validation)

#### The data for validation must be passed to the component as follows

[](#the-data-for-validation-must-be-passed-to-the-component-as-follows)

Os dados para validação devem ser passados ​​para o componente da seguinte forma

```
$data = [
    'email'=> 'hnr.azevedo@gmail.com',
    'password' => 123456,
    'password2' => 123456,
    'phones' => [
        '949164770','949164771','949164772'
    ],
    'birth' => '28/09/1996'
    '_PROVIDER' => 'user',   /* Class responsible for validations */
    '_ROLE' => 'login'       /* Form action */
];
```

### Defining namespace

[](#defining-namespace)

#### To use dynamically to avoid the need to place the entire namespace of a class with rules, you must define the namespace before performing data validation

[](#to-use-dynamically-to-avoid-the-need-to-place-the-entire-namespace-of-a-class-with-rules-you-must-define-the-namespace-before-performing-data-validation)

Para utilização de forma dinamica para evitar a necessidade de colocar o namespace inteiro de uma class com regras, deve-se definir o namespace antes de executar a validação dos dados

### Check data

[](#check-data)

#### Validation errors are returned in an error array, in case there are more than one occurrence, they can be displayed at the same time

[](#validation-errors-are-returned-in-an-error-array-in-case-there-are-more-than-one-occurrence-they-can-be-displayed-at-the-same-time)

Os erros de validação são retornados em uma matriz de erro, caso haja mais de uma ocorrência, eles podem ser exibidos ao mesmo tempo

```
$valid = Validator::namespace('App\\Rules')->execute($data);

if(!$valid){
    $errors = [];
    foreach(Validator::getErrors() as $err => $message){
        $errors[] = [
            'input' => array_keys($message)[0],                 // Return name input error
            'message' => $message[array_keys($message)[0]]      // Return message error
        ];
    }
}
```

### toJson

[](#tojson)

#### Returns a readable Json for validation to be performed on the client side

[](#returns-a-readable-json-for-validation-to-be-performed-on-the-client-side)

Retorna um Json legível para validação a ser realizada no lado do cliente

```
$json = Validator::namespace('App\\Rules')->toJson($data);

/**
 * Result:
 * {
 *     email:{required:true,filter:274,minlength:1},
 *     password:{required:true,maxlength:20,minlength:6},
 *     password2:{required:true,equals:"password"},
 *     remember:{required:false,maxlength:2,minlength:2},
 *     birth:{required:true,type:"date"},
 *     phones:{maxlength:9,minlength:8,required:true,maxcount:3,mincount:2}
 * }
 */
```

### Middleware

[](#middleware)

#### To use HnrAzevedo\\Validator as middleware, it is necessary to define the following information in ServerRequest

[](#to-use-hnrazevedovalidator-as-middleware-it-is-necessary-to-define-the-following-information-in-serverrequest)

Para utilizar o HnrAzevedo\\Validator como middleware, é necessário definir as seguintes informações na ServerRequest

```
/*
 * @property string $namespace
 * @property array $data
 * @property string $language
 */
$serverRequest = $serverRequest->withAttribute('validator',[
    'namespace' => 'HnrAzevedo\\Validator\\Example\\Rules',
    'data' => $data,
    'lang' => 'pt_br'
]);
```

Support
-------

[](#support)

##### Security: If you discover any security related issues, please email  instead of using the issue tracker.

[](#security-if-you-discover-any-security-related-issues-please-email-hnrazevedogmailcom-instead-of-using-the-issue-tracker)

Se você descobrir algum problema relacionado à segurança, envie um e-mail para  em vez de usar o rastreador de problemas.

Credits
-------

[](#credits)

- [Henri Azevedo](https://github.com/hnrazevedo) (Developer)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/hnrazevedo/Validator/blob/master/LICENSE.md) for more information.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

19

Last Release

2014d ago

Major Versions

v1.1.8 → v2.0.02020-10-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/b13ce2d74efc0fe548fc01fa5334a00d9f836a65f42f18c64d3129f7bf1495e3?d=identicon)[hnrazevedo](/maintainers/hnrazevedo)

---

Top Contributors

[![hnrazevedo](https://avatars.githubusercontent.com/u/56831533?v=4)](https://github.com/hnrazevedo "hnrazevedo (73 commits)")

### Embed Badge

![Health badge](/badges/hnrazevedo-validator/health.svg)

```
[![Health](https://phpackages.com/badges/hnrazevedo-validator/health.svg)](https://phpackages.com/packages/hnrazevedo-validator)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
