Skip to content

Added component Validator section #5661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions components/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ The Components
stopwatch
templating/index
translation/index
validator/index
yaml/index

.. include:: /components/map.rst.inc
5 changes: 5 additions & 0 deletions components/map.rst.inc
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,11 @@
* :doc:`/components/translation/usage`
* :doc:`/components/translation/custom_formats`

* :doc:`/components/validator/index`

* :doc:`/components/validator/introduction`
* :doc:`/components/validator/resources`

* :doc:`/components/yaml/index`

* :doc:`/components/yaml/introduction`
Expand Down
8 changes: 8 additions & 0 deletions components/validator/builtin_validators.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.. index::
single: Validator; Built In Validators

Built In Validators
===================

For each validation rule, the component ships a Constraint class and its associated Validator class.
The Constraint object describes the rule to check and the Validator implementation runs the validation logic.
5 changes: 5 additions & 0 deletions components/validator/custom_validation.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.. index::
single: Validator; Custom Validation

Custom Validation
=================
13 changes: 13 additions & 0 deletions components/validator/index.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Validator
=========

.. toctree::
:maxdepth: 2

introduction
resources
metadata
builtin_validators
validation_groups
custom_validation
internationalization
5 changes: 5 additions & 0 deletions components/validator/internationalization.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.. index::
single: Validator; Internationalization

Internationalization
====================
84 changes: 84 additions & 0 deletions components/validator/introduction.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
.. index::
single: Validator
single: Components; Validator

The Validator Component
=======================

The Validator component provides tools to validate values following the
`JSR-303 Bean Validation specification`_. With the component, this is done in two parts:
* ``Contraints``: a constraint describes a rule that need to be validated
* ``Validators``: a list of classes that implement the validation logic for common usages

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

You can install the component in 2 different ways:

* :doc:`Install it via Composer </components/using_components>` (``symfony/validator`` on `Packagist`_);
* Use the official Git repository (https://github.com/symfony/Validator).

.. include:: /components/require_autoload.rst.inc

Usage
-----

The Validator component allows you to use very advanced validation rules, but
it is also really easy to do easy validation tasks. For instance, if you want
to validate that a string is at least 10 character long, the only code you need is::

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Length;

$validator = Validation::createValidator();

$violations = $validator->validateValue('Bernhard', new Length(array('min' => 10)));

if (0 !== count($violations)) {
// there are errors, now you can show them
foreach ($violations as $violation) {
echo $violation->getMessage().'<br>';
}
}

Retrieving a Validator Instance
-------------------------------

The :class:`Symfony\\Component\\Validator\\Validator` class is the main access
point of the Validator component. To create a new instance of this class, it
is recommended to use the :class:`Symfony\\Component\\Validator\\Validation`
class.

You can get a very basic ``Validator`` by calling
:method:`Validation::createValidator() <Symfony\\Component\\Validator\\Validation::createValidator>`::

use Symfony\Component\Validator\Validation;

$validator = Validation::createValidator();

The created validator can be used to validate strings, arrays, numbers, but it
can't validate classes. In order to achieve that, you have to configure the ``Validator``
class. To do that, you can use the :class:`Symfony\\Component\\Validator\\ValidatorBuilder`.
This class can be retrieved by using the
:method:`Validation::createValidatorBuilder() <Symfony\\Component\\Validator\\Validation::createValidatorBuilder>`
method::

use Symfony\Component\Validator\Validation;

$validator = Validation::createValidatorBuilder()
// ... build a custom instance of the Validator
->getValidator();

In the next sections, you'll learn about all things you can configure in the Validator.

Sections
--------

* :doc:`/components/validator/resources`
* :doc:`/components/validator/builtin_validators`
* :doc:`/components/validator/validation_groups`
* :doc:`/components/validator/internationalization`
* :doc:`/components/validator/custom_validation`

.. _`JSR-303 Bean Validation specification`: http://jcp.org/en/jsr/detail?id=303
.. _Packagist: https://packagist.org/packages/symfony/validator
84 changes: 84 additions & 0 deletions components/validator/metadata.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
.. index::
single: Validator; Metadata

Metadata
========

The :class:`Symfony\\Component\\Validator\\Mapping\\ClassMetadata` class represents and manages all the configured constraints on a given class.

Properties
----------

Validating class properties is the most basic validation technique. Validation component
allows you to validate private, protected or public properties. The next
listing shows you how to configure the ``$firstName`` property of an ``Author``
class to have at least 3 characters::

// ...
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
private $firstName;

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('firstName', new Assert\NotBlank());
$metadata->addPropertyConstraint(
'firstName',
new Assert\Length(array("min" => 3))
);
}
}

Getters
-------

Constraints can also be applied to the return value of a method. Symfony
allows you to add a constraint to any public method whose name starts with
"get" or "is". In this guide, both of these types of methods are referred
to as "getters".

The benefit of this technique is that it allows you to validate your object
dynamically. For example, suppose you want to make sure that a password field
doesn't match the first name of the user (for security reasons). You can
do this by creating an ``isPasswordLegal`` method, and then asserting that
this method must return ``true``::

// ...
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addGetterConstraint('passwordLegal', new Assert\True(array(
'message' => 'The password cannot match your first name',
)));
}
}

Now, create the ``isPasswordLegal()`` method and include the logic you need::

public function isPasswordLegal()
{
return $this->firstName !== $this->password;
}

.. note::

The keen-eyed among you will have noticed that the prefix of the getter
("get" or "is") is omitted in the mapping. This allows you to move the
constraint to a property with the same name later (or vice versa) without
changing your validation logic.

Classes
-------

Some constraints apply to the entire class being validated. For example,
the :doc:`Callback </reference/constraints/Callback>` constraint is a generic
constraint that's applied to the class itself. When that class is validated,
methods specified by that constraint are simply executed so that each can
provide more custom validation.
Loading