2
2
single: Validation; Custom constraints
3
3
4
4
How to create a Custom Validation Constraint
5
- --------------------------------------------
5
+ ============================================
6
6
7
7
You can create a custom constraint by extending the base constraint class,
8
- :class: `Symfony\\ Component\\ Validator\\ Constraint `. Options for your
9
- constraint are represented as public properties on the constraint class. For
10
- example, the :doc: `Url</reference/constraints/Url> ` constraint includes
11
- the ``message `` and ``protocols `` properties:
8
+ :class: `Symfony\\ Component\\ Validator\\ Constraint `.
9
+ As an example we're going to create a simple validator that checks if string contains only alphanumeric characters.
12
10
13
- .. code-block :: php
11
+ Creating Constraint class
12
+ -------------------------
14
13
15
- namespace Symfony\Component\Validator\Constraints;
14
+ First you need to create a Constraint class and extend :class: `Symfony\\ Component\\ Validator\\ Constraint `::
15
+
16
+ namespace Acme\D emoBundle\V alidator\C onstraints;
16
17
17
18
use Symfony\C omponent\V alidator\C onstraint;
18
19
19
20
/**
20
21
* @Annotation
21
22
*/
22
- class Protocol extends Constraint
23
+ class ContainsAlphanumeric extends Constraint
23
24
{
24
- public $message = 'The value "%protocol%" is not a valid protocol';
25
- public $protocols = array('http', 'https', 'ftp', 'ftps');
25
+ public $message = 'Missing at least one alphanumeric character in "%string%" string';
26
26
}
27
27
28
28
.. note ::
29
29
30
30
The ``@Annotation `` annotation is necessary for this new constraint in
31
31
order to make it available for use in classes via annotations.
32
+ Options for your constraint are represented as public properties on the constraint class.
32
33
34
+ Creating Validator itself
35
+ -------------------------
36
+
33
37
As you can see, a constraint class is fairly minimal. The actual validation is
34
38
performed by a another "constraint validator" class. The constraint validator
35
39
class is specified by the constraint's ``validatedBy() `` method, which
36
- includes some simple default logic:
37
-
38
- .. code-block :: php
40
+ includes some simple default logic::
39
41
40
42
// in the base Symfony\Component\Validator\Constraint class
41
43
public function validatedBy()
@@ -47,22 +49,19 @@ In other words, if you create a custom ``Constraint`` (e.g. ``MyConstraint``),
47
49
Symfony2 will automatically look for another class, ``MyConstraintValidator ``
48
50
when actually performing the validation.
49
51
50
- The validator class is also simple, and only has one required method: ``isValid ``.
51
- Furthering our example, take a look at the ``ProtocolValidator `` as an example:
52
+ The validator class is also simple, and only has one required method: ``isValid ``::
52
53
53
- .. code-block :: php
54
-
55
- namespace Symfony\Component\Validator\Constraints;
54
+ namespace Acme\DemoBundle\Validator\Constraints;
56
55
57
56
use Symfony\Component\Validator\Constraint;
58
57
use Symfony\Component\Validator\ConstraintValidator;
59
58
60
- class ProtocolValidator extends ConstraintValidator
59
+ class ContainsAlphanumericValidator extends ConstraintValidator
61
60
{
62
61
public function isValid($value, Constraint $constraint)
63
62
{
64
- if (!in_array($ value, $constraint->protocols )) {
65
- $this->setMessage($constraint->message, array('%protocol%' => $value) );
63
+ if (!preg_match('/^[a-zA-Za0-9]+$/', $ value, $matches )) {
64
+ $this->setMessage($constraint->message);
66
65
67
66
return false;
68
67
}
@@ -75,6 +74,36 @@ Furthering our example, take a look at the ``ProtocolValidator`` as an example:
75
74
76
75
Don't forget to call ``setMessage `` to construct an error message when the
77
76
value is invalid.
77
+
78
+ Using newly created validator
79
+ -----------------------------
80
+
81
+ Using custom validators is very easy, just as the ones provided by Symfony2 itself::
82
+
83
+ namespace Acme\DemoBundle\Entity;
84
+
85
+ use Doctrine\ORM\Mapping as ORM;
86
+ use Symfony\Component\Validator\Constraints as Assert;
87
+ use Acme\DemoBundle\Validator\Constraints as AcmeAssert;
88
+
89
+ class AcmeEntity
90
+ {
91
+ /**
92
+ * @ORM\Id
93
+ * @ORM\GeneratedValue
94
+ * @ORM\Column(name="id", type="integer")
95
+ */
96
+ protected $id;
97
+
98
+ /**
99
+ * @Assert\NotBlank
100
+ * @AcmeAssert\ContainsAlphanumeric
101
+ * @ORM\Column(name="name", type="string", length=100)
102
+ */
103
+ protected $name;
104
+
105
+ // ...
106
+ }
78
107
79
108
Constraint Validators with Dependencies
80
109
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0 commit comments