Skip to content

Commit ceb95cd

Browse files
Bernhard Schussekfabpot
authored andcommitted
Started rewriting the Validator docs
1 parent 434a1de commit ceb95cd

File tree

3 files changed

+374
-0
lines changed

3 files changed

+374
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
AssertTrue
2+
==========
3+
4+
Validates that a value is `true`.
5+
6+
[yml]
7+
properties:
8+
termsAccepted:
9+
- AssertTrue: ~
10+
11+
Options
12+
-------
13+
14+
* `message`: The error message if validation fails
15+
16+
17+
Example 1 (YAML)
18+
----------------
19+
20+
This constraint is very useful to execute custom validation logic. You can
21+
put the logic in a method which returns either `true` or `false`.
22+
23+
**Listing 1**
24+
25+
[php]
26+
// Application/HelloBundle/Author.php
27+
namespace Application\HelloBundle;
28+
29+
class Author
30+
{
31+
protected $token;
32+
33+
public function isTokenValid()
34+
{
35+
return $this->token == $this->generateToken();
36+
}
37+
}
38+
39+
Then you can constrain this method with `AssertTrue`.
40+
41+
**Listing 2**
42+
43+
[yaml]
44+
# Application/HelloBundle/Resources/config/validation.yml
45+
Application\HelloBundle\Author:
46+
getters:
47+
tokenValid:
48+
- AssertTrue: { message: "The token is invalid" }
49+
50+
If the validation of this method fails, you will see a message similar to this:
51+
52+
Application\HelloBundle\Author.tokenValid:
53+
This value should not be null
54+
55+
Example 2 (XML)
56+
---------------
57+
58+
Example 1 can also be solved using XML.
59+
60+
**Listing 3**
61+
62+
[xml]
63+
<!-- Application/HelloBundle/Resources/config/validation.xml -->
64+
<class name="Application\HelloBundle\Author">
65+
<getter name="tokenValid">
66+
<constraint name="True">
67+
<option name="message">The token is invalid</option>
68+
</constraint>
69+
</getter>
70+
</class>
71+
72+
Example 3 (Docblock Annotations)
73+
--------------------------------
74+
75+
The following listing shows how Listing 2 can be mapped using Docblock
76+
Annotations.
77+
78+
**Listing 4**
79+
80+
[php]
81+
// Application/HelloBundle/Author.php
82+
namespace Application\HelloBundle;
83+
84+
class Author
85+
{
86+
protected $token;
87+
88+
/**
89+
* @Validation({ @AssertTrue(message = "The token is invalid") })
90+
*/
91+
public function isTokenValid()
92+
{
93+
return $this->token == $this->generateToken();
94+
}
95+
}
96+
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
Collection
2+
==========
3+
4+
Validates array entries against different constraints.
5+
6+
[yml]
7+
- Collection:
8+
fields:
9+
key1:
10+
- NotNull: ~
11+
key2:
12+
- MinLength: 10
13+
14+
Options
15+
-------
16+
17+
* `fields` (required): An associative array of array keys and one or more
18+
constraints
19+
* `allowMissingFields`: Whether some of the keys may not be present in the
20+
array. Default: `false`
21+
* `allowExtraFields`: Whether the array may contain keys not present in the
22+
`fields` option. Default: `false`
23+
* `missingFieldsMessage`: The error message if the `allowMissingFields`
24+
validation fails
25+
* `allowExtraFields`: The error message if the `allowExtraFields` validation
26+
fails
27+
28+
Example 1 (YAML):
29+
-----------------
30+
31+
**Listing 1**
32+
33+
[yml]
34+
# Application/HelloBundle/Resources/config/validation.yml
35+
Application\HelloBundle\Author:
36+
properties:
37+
options:
38+
- Collection:
39+
fields:
40+
firstName:
41+
- NotNull: ~
42+
lastName:
43+
- NotNull: ~
44+
- MinLength: 4
45+
allowMissingFields: true
46+
47+
The following object would fail the validation.
48+
49+
**Listing 2**
50+
51+
[php]
52+
$author = new Author();
53+
$author->options['firstName'] = null;
54+
$author->options['lastName'] = 'foo';
55+
56+
print $validator->validate($author);
57+
58+
You should see the following error messages:
59+
60+
Application\HelloBundle\Author.options[firstName]:
61+
This value should not be null
62+
Application\HelloBundle\Author.options[lastName]:
63+
This value is too short. It should have 4 characters or more
64+
65+
Example 2 (XML):
66+
----------------
67+
68+
This example shows the same mapping as in Example 1 using XML.
69+
70+
**Listing 3**
71+
72+
[xml]
73+
<!-- Application/HelloBundle/Resources/config/validation.xml -->
74+
<class name="Application\HelloBundle\Author">
75+
<property name="options">
76+
<constraint name="Collection">
77+
<option name="fields">
78+
<value key="firstName">
79+
<constraint name="NotNull" />
80+
</value>
81+
<value key="lastName">
82+
<constraint name="NotNull" />
83+
<constraint name="MinLength">4</constraint>
84+
</value>
85+
</option>
86+
<option name="allowMissingFields">true</option>
87+
</constraint>
88+
</property>
89+
</class>
90+
91+
Example 3 (Docblock Annotations):
92+
---------------------------------
93+
94+
This example shows the mapping from Example 1 with Docblock Annotations.
95+
96+
**Listing 4**
97+
98+
[php]
99+
// Application/HelloBundle/Author.php
100+
namespace Application\HelloBundle;
101+
102+
class Author
103+
{
104+
/**
105+
* @Validation({ @Collection(
106+
* fields = {
107+
* "firstName" = @NotNull,
108+
* "lastName" = { @NotBlank, @MinLength(4) }
109+
* },
110+
* allowMissingFields = true
111+
* )})
112+
*/
113+
private $options = array();
114+
}

guides/en/Validator/Overview.markdown

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
The Validator
2+
=============
3+
4+
Validation is a very common task in web applications. Data entered in forms
5+
needs to be validated. Data also needs to be validated before it is written
6+
into a database or passed to a web service.
7+
8+
Symfony2 comes with a new Validator component that makes this task very easy.
9+
This component is based on the [JSR303 Bean Validation specification][1].
10+
What? A Java specification in PHP? You heard right, but it's not as bad as it
11+
sounds. Let's look at how we use it in PHP.
12+
13+
Constraints
14+
-----------
15+
16+
The Validator is designed to validate objects against different *constraints*.
17+
In real life, a constraint would be: "The cake must not be burned". In
18+
Symfony2, constraints are very similar: They are assertions that a specific
19+
condition is true.
20+
21+
Constraints can be put on properties of a class, on public getters and on the
22+
class itself. Property and getter constraints obviously can only be used to
23+
validate a single value. Class constraints, on the other hand, can validate
24+
the whole state of an object at once, with all its properties and methods.
25+
26+
>**NOTE**
27+
>As "getter" the validator accepts any method with the prefix "get" or "is."
28+
29+
The following constraints are natively available in Symfony2:
30+
31+
* [AssertFalse](Constraints/AssertFalse)
32+
* [AssertTrue](Constraints/AssertTrue)
33+
* [AssertType](Constraints/AssertType)
34+
* [Choice](Constraints/Choice)
35+
* [Collection](Constraints/Collection)
36+
* [Date](Constraints/Date)
37+
* [DateTime](Constraints/DateTime)
38+
* [Email](Constraints/Email)
39+
* [File](Constraints/File)
40+
* [Max](Constraints/Max)
41+
* [MaxLength](Constraints/MaxLength)
42+
* [Min](Constraints/Min)
43+
* [MinLength](Constraints/MinLength)
44+
* [NotBlank](Constraints/NotBlank)
45+
* [NotNull](Constraints/NotNull)
46+
* [Regex](Constraints/Regex)
47+
* [Time](Constraints/Time)
48+
* [Url](Constraints/Url)
49+
* [Valid](Constraints/Valid)
50+
51+
Mapping
52+
-------
53+
54+
The mapping of constraints to classes, properties and getters takes place
55+
in the mapping. Symfony2 supports YAML, XML, PHP and Docblock Annotations as
56+
mapping drivers.
57+
58+
Let's look at the YAML driver for now. We start with a simple example class
59+
`Author`.
60+
61+
**Listing 1**
62+
63+
[php]
64+
// Application/HelloBundle/Author.php
65+
namespace Application\HelloBundle;
66+
67+
class Author
68+
{
69+
public $firstName;
70+
public $lastName;
71+
72+
public function getFullName()
73+
{
74+
return $this->firstName.' '.$this->lastName;
75+
}
76+
}
77+
78+
Now we want to put some simple constraints on this class.
79+
80+
* The first and last name should not be blank
81+
82+
* The first and last name together should have at least 10 characters
83+
84+
To map these constraints with YAML, create a new `validation.yml` mapping file
85+
in your bundle.
86+
87+
**Listing 2**
88+
89+
[yml]
90+
# Application/HelloBundle/Resources/config/validation.yml
91+
Application\HelloBundle\Author:
92+
properties:
93+
firstName:
94+
- NotBlank: ~
95+
lastName:
96+
- NotBlank: ~
97+
getters:
98+
fullName:
99+
- MinLength: 10
100+
101+
As you can see, the mapping is very straight-forward.
102+
103+
>**NOTE**
104+
>The keen-eyed among you will have noticed that the prefix of the getter
105+
>("get" or "is") is omitted in the mapping. This allows you to move the
106+
>constraint to a property with the same name later (or vice versa) without
107+
>changing your validation logic.
108+
109+
This guide uses YAML mappings throughout all examples. There will be dedicated
110+
chapters about the XML, PHP and Annotation drivers.
111+
112+
The Validator
113+
-------------
114+
115+
Objects with constraints are validated by the `Validator` class. If you use
116+
Symfony2, this class is already registered as a service in the Dependency
117+
Injection Container. To enable the service, add the following lines to your
118+
configuration:
119+
120+
**Listing 3**
121+
122+
[yml]
123+
# config.yml
124+
web.config:
125+
validation: true
126+
127+
Then you can get the validator from the container and start validating your
128+
objects.
129+
130+
**Listing 4**
131+
132+
[php]
133+
$validator = $container->getService('validator');
134+
$author = new Author();
135+
136+
print $validator->validate($author);
137+
138+
The `validate()` method returns a `ConstraintViolationList` object. This object
139+
behaves exactly like an array. You can iterate over it, and you can even print
140+
it in a nicely formatted manner. Every element of the list corresponds to
141+
one validation error. If the list is empty, it's time to dance, because then
142+
validation succeeded.
143+
144+
The above call will output something similar to this:
145+
146+
Application\HelloBundle\Author.firstName:
147+
This value should not be blank
148+
Application\HelloBundle\Author.lastName:
149+
This value should not be blank
150+
Application\HelloBundle\Author.fullName:
151+
This value is too short. It should have 10 characters or more
152+
153+
If you fill the object with correct values, you will see that the validation
154+
errors disappear.
155+
156+
### Validating Properties
157+
158+
TODO
159+
160+
### Validating Values
161+
162+
TODO
163+
164+
[1]: http://jcp.org/en/jsr/detail?id=303

0 commit comments

Comments
 (0)