@@ -6,7 +6,7 @@ How to create a Custom Validation Constraint
6
6
7
7
You can create a custom constraint by extending the base constraint class,
8
8
:class: `Symfony\\ Component\\ Validator\\ Constraint `.
9
- As an example we're going to create a simple validator that checks if string
9
+ As an example we're going to create a simple validator that checks if a string
10
10
contains only alphanumeric characters.
11
11
12
12
Creating Constraint class
@@ -23,17 +23,18 @@ First you need to create a Constraint class and extend :class:`Symfony\\Componen
23
23
*/
24
24
class ContainsAlphanumeric extends Constraint
25
25
{
26
- public $message = 'Missing at least one alphanumeric character in "%string%" string ';
26
+ public $message = 'The string "%string%" contains an illegal character: it can only contain letters or numbers. ';
27
27
}
28
28
29
29
.. note ::
30
30
31
31
The ``@Annotation `` annotation is necessary for this new constraint in
32
32
order to make it available for use in classes via annotations.
33
- Options for your constraint are represented as public properties on the constraint class.
33
+ Options for your constraint are represented as public properties on the
34
+ constraint class.
34
35
35
- Creating Validator itself
36
- -------------------------
36
+ Creating the Validator itself
37
+ -----------------------------
37
38
38
39
As you can see, a constraint class is fairly minimal. The actual validation is
39
40
performed by a another "constraint validator" class. The constraint validator
@@ -76,8 +77,8 @@ The validator class is also simple, and only has one required method: ``isValid`
76
77
Don't forget to call ``setMessage `` to construct an error message when the
77
78
value is invalid.
78
79
79
- Using newly created validator
80
- -----------------------------
80
+ Using the new Validator
81
+ -----------------------
81
82
82
83
Using custom validators is very easy, just as the ones provided by Symfony2 itself:
83
84
@@ -147,6 +148,10 @@ Using custom validators is very easy, just as the ones provided by Symfony2 itse
147
148
}
148
149
}
149
150
151
+ If your constraint contains options, then they should be public properties
152
+ on the custom Constraint class you created earlier. These options can be
153
+ configured like options on core Symfony constraints.
154
+
150
155
Constraint Validators with Dependencies
151
156
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152
157
0 commit comments