PHPackages                             tobias/zend-validator-doctrine - 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. tobias/zend-validator-doctrine

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

tobias/zend-validator-doctrine
==============================

Validate doctrine entities with Zend\\Validator

03PHP

Since Jun 27Pushed 6y agoCompare

[ Source](https://github.com/tobias-trozowski/zend-validator-doctrine)[ Packagist](https://packagist.org/packages/tobias/zend-validator-doctrine)[ RSS](/packages/tobias-zend-validator-doctrine/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependenciesVersions (1)Used By (0)

Zend Validator Doctrine
=======================

[](#zend-validator-doctrine)

[![Build Status](https://camo.githubusercontent.com/b7753a54ac5c705e90d76b8f6db0a12562d68e6deabd340b5deab9fcc2a70798/68747470733a2f2f7472617669732d63692e636f6d2f746f626961732d74726f7a6f77736b692f7a656e642d76616c696461746f722d646f637472696e652e737667)](https://travis-ci.com/tobias-trozowski/zend-validator-doctrine)

Inspired and based on the famous [DoctrineModule](https://github.com/doctrine/DoctrineModule).

This package provides three validators that work out the box: `Tobias\Zend\Validator\Doctrine\ObjectExists` and `Tobias\Zend\Validator\Doctrine\NoObjectExists` which implements a check if an entity exists or does not exists in the database, respectively, and `Tobias\Zend\Validator\Doctrine\UniqueObject` which implements a check if a value is only used in one object. They behave like any other standard Zend validator.

All three validators accept the following options :

- `object_repository` : an instance of an object repository.
- `fields` : an array that contains all the fields that are used to check if the entity exists (or does not).

The `Tobias\Zend\Validator\Doctrine\UniqueObject` also needs the following option:

- `object_manager` : an instance of an object manager.

For the `use_context` option and other specifics to `Tobias\Zend\Validator\Doctrine\UniqueObject` see [below](#uniqueobject).

> Tip : to get an object repository from an object manager you call the `getRepository` function of any valid object manager instance, passing it the FQCN of the class. For instance, in the context of Doctrine 2 ORM, here is how you get the `object_repository` of the 'Application\\Entity\\User' entity:

```
$repository = $entityManager->getRepository('Application\Entity\User');
```

### Simple usage

[](#simple-usage)

You can directly instantiate a validator the following way:

```
$validator = new \Tobias\Zend\Validator\Doctrine\ObjectExists([
    'object_repository' => $objectManager->getRepository('Application\Entity\User'),
    'fields' => ['email'],
]);

var_dump($validator->isValid('test@example.com')); // dumps 'true' if an entity matches
var_dump($validator->isValid(['email' => 'test@example.com'])); // dumps 'true' if an entity matches
```

### Use together with Zend Framework 2 forms

[](#use-together-with-zend-framework-2-forms)

Of course, validators are especially useful when paired with forms. To add a `NoObjectExists` validator to a Zend Framework form element:

```
namespace Application\Form;

use Tobias\Zend\Validator\Doctrine\NoObjectExists as NoObjectExistsValidator;
use Zend\Form\Form;
use Zend\ServiceManager\ServiceManager;
use Application\Entity;

class User extends Form
{
    public function __construct(ServiceManager $serviceManager)
    {
        parent::__construct('my-form');

        // Add an element
        $this->add([
            'type'    => 'Zend\Form\Element\Email',
            'name'    => 'email',
            'options' => [
                'label' => 'Email',
            ],
            'attributes' => [
                'required' => 'required',
            ],
        ]);

        // add other elements (submit, CSRF…)

        // Fetch any valid object manager from the Service manager
        $entityManager = $serviceManager->get('doctrine.entitymanager.orm_default');

        // Now get the input filter of the form, and add the validator to the email input
        $emailInput = $this->getInputFilter()->get('email');

        $noObjectExistsValidator = new NoObjectExistsValidator([
            'object_repository' => $entityManager->getRepository(Entity\User::class),
            'fields'            => 'email',
        ]);

        $emailInput
            ->getValidatorChain()
            ->attach($noObjectExistsValidator);
    }
}
```

If you are using fieldset's you can directly add the validator using the array notation. For instance in the `getInputFilterSpecification` function, as shown here:

```
namespace Application\Form;

use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Application\Entity;

class UserFieldset extends Fieldset implements InputFilterProviderInterface
{
    protected $serviceManager;

    public function __construct(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;

        parent::__construct('my-fieldset');

        // Add an element
        $this->add([
            'type'    => 'Zend\Form\Element\Email',
            'name'    => 'email',
            'options' => [
                'label' => 'Email',
            ],
            'attributes' => [
                'required' => 'required',
            ],
        ]);
    }

    public function getInputFilterSpecification()
    {
        $entityManager = $this->serviceManager->get('doctrine.entitymanager.orm_default');

        return [
            'email' => [
                'validators' => [
                    [
                        'name' => 'Tobias\Zend\Validator\Doctrine\NoObjectExists',
                        'options' => [
                            'object_repository' => $entityManager->getRepository(Entity\User::class),
                            'fields' => 'email',
                        ],
                    ],
                ],
            ],
        ];
    }
}
```

You can change the default message of the validators like this:

```
// For NoObjectExists validator (using array notation) :
'validators' => [
    [
        'name' => 'Tobias\Zend\Validator\Doctrine\NoObjectExists',
        'options' => [
            'object_repository' => $this->getEntityManager()->getRepository('Application\Entity\User'),
            'fields' => 'email',
            'messages' => [
                'objectFound' => 'A user with this email already exists.',
            ],
        ],
    ],
],

// For ObjectExists validator (using object notation) :
$objectExistsValidator = new \Tobias\Zend\Validator\Doctrine\ObjectExists([
    'object_repository' => $entityManager->getRepository('Application\Entity\User'),
    'fields'            => 'email',
]);

**$objectExistsValidator->setMessage('noObjectFound', 'Email was not found.');**
```

### UniqueObject

[](#uniqueobject)

There are two things you have to think about when using `Tobias\Zend\Validator\Doctrine\UniqueObject`; As mentioned above you have to pass an ObjectManager as `object_manager` option and second you have to pass a value for every identifier your entity has.

- If you leave out the `use_context` option or set it to `false` you have to pass an array containing the `fields`- and `identifier`-values into `isValid()`. When using `Zend\Form` this behaviour is needed if you're using fieldset's.
- If you set the `use_context` option to `true` you have to pass the `fields`-values as first argument and an array containing the `identifier`-values as second argument into `isValid()`. When using `Zend\Form` without fieldset's, this behaviour would be needed.

**Important:** Whatever you choose, please ensure that the `identifier`-values are named by the field-names, not by the database-column.

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/0355d9a2db10711c7f3d0ac8c97e9fbda01838b80455740b98f5a8b335b921cc?d=identicon)[tobias-trozowski](/maintainers/tobias-trozowski)

---

Top Contributors

[![tobias-trozowski](https://avatars.githubusercontent.com/u/3001979?v=4)](https://github.com/tobias-trozowski "tobias-trozowski (1 commits)")

### Embed Badge

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

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

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[nette/forms

📝 Nette Forms: generating, validating and processing secure forms in PHP. Handy API, fully customizable, server &amp; client side validation and mature design.

54013.2M450](/packages/nette-forms)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)

PHPackages © 2026

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