PHPackages                             paliari/doctrine-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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. paliari/doctrine-validator

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

paliari/doctrine-validator
==========================

Advanced model validator for Doctrine ORM (based on ActiveRecord)

4.0.2(3y ago)33.6k↓100%1MITPHPPHP ^8.0CI failing

Since Oct 6Pushed 3y ago2 watchersCompare

[ Source](https://github.com/paliari/doctrine-validator)[ Packagist](https://packagist.org/packages/paliari/doctrine-validator)[ Docs](https://github.com/paliari/doctrine-validator)[ RSS](/packages/paliari-doctrine-validator/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (4)Versions (40)Used By (1)

doctrine-validator
==================

[](#doctrine-validator)

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

[](#installation)

```
composer require paliari/doctrine-validator

```

Configuration
-------------

[](#configuration)

Include the TraitValidatorModel in your model

```
// Create your model extended to AbstractRansackModel.
class YourModel
{
    use \Paliari\Doctrine\TraitValidatorModel;

    //... fields ...

    /**
     * Override the method getEm is required.
     * You must return your EntityManager in this method
     *
     * @return \Doctrine\ORM\EntityManager
     */
    public static function getEM()
    {
        // return EntityManager
    }

}
```

Or you can make your model class extends from AbstractValidatorModel:

```
class YourModel extends \Paliari\Doctrine\AbstractValidatorModel
{
    //... fields ...

    /**
     * Override the method getEm is required.
     * You must return your EntityManager in this method
     *
     * @return \Doctrine\ORM\EntityManager
     */
    public static function getEM()
    {
        // return EntityManager
    }
}
```

### Initialize validator

[](#initialize-validator)

Add in your bootstrap:

```
$eventManager = $entityManager->getEventManager();
$eventManager->addEventSubscriber(new \Paliari\Doctrine\ModelValidatorEventSubscriber());
```

Usage
-----

[](#usage)

### Validators

[](#validators)

Create a `protected static` property inside your model to validate. See the available options and examples:

- **validates\_presence\_of**

    - Options: `if`, `unless`, `on`
    - Example:

        ```
        protected static $validates_presence_of = [
            'email',
            'last_login' => ['on' => 'update'],
            'nike_name' => ['unless' => 'name']
        ];
        ```
- **validates\_size\_of** *alias to validates\_length\_of*

    - Options: `minimum`, `maximum`, `in|within`
    - Example:

        ```
        protected static $validates_length_of = [
            'name' => ['minimum' => 10, 'maximum' => 100],
            'nike_name' => ['in' => [3, 20]]
        ];
        ```

        > the `maximum` option is automatically setted by the field doc block
- **validates\_inclusion\_of**

    - Options: `in|within`, `allow_nil`, `allow_blank`
    - Example:

        ```
        protected static $validates_inclusion_of = [
            'type' => ['in' => [1, 2, 3, 4]],
            'value' => ['in' => [1, 2, 3, 4], 'allow_nil' => true],
            'field_name' => ['in' => ['a', 'b', 'c'], 'allow_blank' => true]
        ];
        ```

    > the `boolean` fields are automatically setted as `true|false`
- **validates\_exclusion\_of**

    - Options: `in|within`, `allow_nil`, `allow_blank`
    - Example:

        ```
        protected static $validates_exclusion_of = [
            'field_name' => ['in' => ['a', 'b', 'c'], 'allow_blank' => true]
        ];
        ```
- **validates\_format\_of**

    - Options: `with`, `without`

        - Values: `email`, `url`, `integer`, `boolean`, `ip`, `/[0-9a-z]/`
    - Example:

        ```
        protected static $validates_format_of = [
            'email' => ['with' => 'email'],
            'field_url' => ['with' => 'url'],
            'field_name' => ['without' => 'float']
        ];
        ```
- **validates\_numericality\_of**

    - Options: `greater_than`, `greater_than_or_equal_to`, `less_than`, `less_than_or_equal_to`, `equal_to`, `other_than`, `only_integer`
    - Example:

        ```
        protected static $validates_numericality_of = [
            'ammount' => ['greater_than' => 5],
            'another_field' => ['only_integer' => true]
        ];
        ```
- **validates\_uniqueness\_of**

    - Options: `scope`
    - Example:

        ```
        protected static $validates_uniqueness_of = [
            'email',
            'number' => ['scope' => ['year']],
        ];
        ```
- **validates\_custom**

    - Example:

        ```
        protected static $validates_custom = ['yourMethodName', 'otherYourMethodName'];

        public function yourMethodName() {
          if ($name == 'example') {
            $this->errors->add('name', '"name" cannot be "example"');
          }
        }

        public function otherYourMethodName() {
          // Do something here
        }
        ```

> There is also a list of default options supported by every validator: 'if', 'unless', 'on', 'allow\_nil' or 'allow\_blank'

### Callbacks

[](#callbacks)

Create a `protected static` property with the callbacks inside your model. See the available options and examples:

- **before\_validation**Execute before validation

    - Example:

        ```
        protected static $before_validation = ['yourCallbackName'];

        public function yourCallbackName() { /* Do something here */}
        ```
- **after\_validation**Execute after validation

    - Example:

        ```
        protected static $after_validation = ['anotherCallbackName'];
        ```
- **before\_validation\_on\_create**Execute before validation only create

    - Example:

        ```
        protected static $before_validation_on_create = ['yourCallbackName'];
        ```
- **after\_validation\_on\_create**Execute after validation only create

    - Example:

        ```
        protected static $after_validation_on_create = ['yourCallbackName'];
        ```
- **before\_validation\_on\_update**Execute before validation only update

    - Example:

        ```
        protected static $before_validation_on_update = ['yourCallbackName'];
        ```
- **after\_validation\_on\_update**Execute after validation only update

    - Example:

        ```
        protected static $after_validation_on_update = ['yourCallbackName'];
        ```
- **before\_validation\_on\_remove**Execute before validation only remove

    - Example:

        ```
        protected static $before_validation_on_remove = ['yourCallbackName'];
        ```
- **after\_validation\_on\_remove**Execute after validation only remove

    - Example:

        ```
        protected static $after_validation_on_remove = ['yourCallbackName'];
        ```

### Custom Validators

[](#custom-validators)

Para adicionar validator customizado é só uar o método statico no model *ModelName::addCustomValidator*passando como argumento um *callable* que recebe como parametro o $model.

To add custom validator just use the static method in model ModelName :: addCustomValidator passing as argument a callable that takes $model as parameter.

Example:

```
MyModel::addCustomValidator(function($model) {
  if ($model->isNewRecord()) {
      if (!MyValidator::instance()->isValid($model)) {
          foreach (MyValidator::instance()->getMessages() as $k => $item) {
              $model->errors->add($k, $item);
          }
      }
  }
});

// ou
MyModel::addCustomValidator('MyValidator::validate');
```

Development
-----------

[](#development)

### Install dependencies

[](#install-dependencies)

```
docker-compose -f docker-compose-cli.yml run --rm cli composer install
```

### Testing

[](#testing)

```
docker-compose -f docker-compose-cli.yml run --rm cli ./vendor/bin/phpunit
```

### Publish a new version

[](#publish-a-new-version)

```
# Generate a new tag
docker-compose -f docker-compose-cli.yml run --rm cli ./vendor/bin/bump -g --version patch|minor|major

git push && git push --tags
```

Authors
-------

[](#authors)

- [Marcos Paliari](http://paliari.com.br)
- [Daniel Fernando Lourusso](http://dflourusso.com.br)

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 95.2% 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 ~58 days

Recently: every ~38 days

Total

38

Last Release

1361d ago

Major Versions

0.0.1 → 1.0.12016-10-07

1.4.5 → 2.0.02021-02-04

2.1.1 → 3.0.02022-03-20

3.0.2 → 4.0.02022-08-21

PHP version history (4 changes)1.3.0PHP ^7.1

1.4.0PHP ^7.3

2.0.0PHP ^7.3|^8.0

2.1.0PHP ^8.0

### Community

Maintainers

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

---

Top Contributors

[![paliari](https://avatars.githubusercontent.com/u/2801041?v=4)](https://github.com/paliari "paliari (157 commits)")[![dflourusso](https://avatars.githubusercontent.com/u/5544901?v=4)](https://github.com/dflourusso "dflourusso (8 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[api-platform/doctrine-orm

Doctrine ORM bridge

243.1M39](/packages/api-platform-doctrine-orm)[happyr/entity-exists-validation-constraint

Verify that your entity exists

31180.4k](/packages/happyr-entity-exists-validation-constraint)

PHPackages © 2026

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