From 155088a05196eba02f1414b394a4deb2f63289a2 Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Fri, 2 Jul 2010 19:44:44 +0200 Subject: [PATCH 1/3] Started rewriting the Validator docs --- guides/en/Validator.markdown | 411 ------------------ .../Validator/Constraints/AssertTrue.markdown | 96 ++++ .../Validator/Constraints/Collection.markdown | 114 +++++ guides/en/Validator/Overview.markdown | 164 +++++++ 4 files changed, 374 insertions(+), 411 deletions(-) delete mode 100644 guides/en/Validator.markdown create mode 100644 guides/en/Validator/Constraints/AssertTrue.markdown create mode 100644 guides/en/Validator/Constraints/Collection.markdown create mode 100644 guides/en/Validator/Overview.markdown diff --git a/guides/en/Validator.markdown b/guides/en/Validator.markdown deleted file mode 100644 index a02430317a3..00000000000 --- a/guides/en/Validator.markdown +++ /dev/null @@ -1,411 +0,0 @@ -Validator -========= - -The Basics ----------- - -The new Validator component is based on the [JSR303 Bean Validation -specification][1]. What? A Java specification in PHP? You heard right, but -it's not as bad as it sounds. Let's look at how we use it in PHP. - -The Validator is designed to validate objects against different constraints. -These constraints can be put on the class itself, on properties and on -methods prefixed with "get" or "is". Let's look at a sample configuration. - - [php] - class Author - { - /** - * @Validation({ - * @NotBlank, - * @MinLength(4) - * }) - */ - public $firstName; - - /** - * @Validation({ - * @Email(message="Ok, seriously now. Your email address please") - * }) - */ - public function getEmail() - { - return 'foobar'; - } - } - -This snippet shows a very simple `Author` class with a property and a getter. -Each constraint has a name, most of them also have a couple of options. Here we -configured the constraints with annotations, but Symfony2 also offers many -other configuration drivers. - -Because the annotation driver depends on the Doctrine library, it is not enabled -by default. You can enable it in your `config.yml`: - - [yml] - # hello/config/config.yml - web.validation: - annotations: true - -Now let's try to validate an object. - - [php] - $validator = $this->container->getValidatorService(); - - $author = new Author(); - $author->firstName = 'B.'; - - print $validator->validate($author); - -You should see the following output. - - Author.firstName: - This value is too short. It should have 4 characters or more - Author.email: - Ok, seriously now. Your email address please - -The `validate()` method returns a `ConstraintViolationList` object that can -simply be printed or processed in your code. That was easy! - -The Constraints ---------------- - -Symfony bundles many different constraints. The following list will show you -which ones are available and how you can use and configure them. Some -constraints have a default option. If you only set this option, you can leave -away the option name. - - [php] - /** @Validation({ @Min(limit=3) }) */ - -is identical to - - [php] - /** @Validation({ @Min(3) }) */ - - -### AssertFalse - -Validates that a value is `false`. Very useful for testing return values of -methods. - - [php] - /** @Validation({ @AssertFalse }) */ - public function isInjured(); - -Options: - - * message: The error message if validation fails - -### AssertTrue - -Works like `AssertFalse`. - -### NotBlank - -Validates that a value is not empty. - - [php] - /** @Validation({ @NotBlank }) */ - private $firstName; - -Options: - - * message: The error message if validation fails - -### Blank - -Works like `NotBlank`. - -### NotNull - -Validates that a value is not `NULL`. - - [php] - /** @Validation({ @NotNull }) */ - private $firstName; - -### Null - -Works like `NotNull`. - -### AssertType - -Validates that a value has a specific data type. - - [php] - /** @Validation({ @AssertType("integer") }) */ - private $age; - -Options: - - * type (default): The type - -### Choice - -Validates that a value is one or more of a list of choices. - - [php] - /** @Validation({ @Choice({"male", "female"}) }) */ - private $gender; - -Options: - - * choices (default): The available choices - * callback: Can be used instead of `choices`. A static callback method - returning the choices. If you set this to a string, the method is expected - to be in the validated class. - * multiple: Whether multiple choices are allowed. Default: `false` - * min: The minimum amount of selected choices - * max: The maximum amount of selected choices - * message: The error message if validation fails - * minMessage: The error message if `min` validation fails - * maxMessage: The error message if `max` validation fails - -### Valid - -Validates that an object is valid. Can be put on properties or getters to -validate related objects - - [php] - /** @Validation({ @Valid }) */ - private $address; - -Options: - - * class: The expected class of the object (optional) - * message: The error message if the class doesn't match - -### Collection - -Validates array entries against different constraints. - - [php] - /** - * @Validation({ @Collection( - * fields = { - * "firstName" = @NotNull, - * "lastName" = { @NotBlank, @MinLength(4) } - * }, - * allowMissingFields = true - * )}) - */ - private $options = array(); - -Options: - - * fields (default): An associative array of array keys and one or more - constraints - * allowMissingFields: Whether some of the keys may not be present in the - array. Default: `false` - * allowExtraFields: Whether the array may contain keys not present in the - `fields` option. Default: `false` - * missingFieldsMessage: The error message if the `allowMissingFields` - validation fails - * allowExtraFields: The error message if the `allowExtraFields` validation - fails - -### Date - -Validates that a value is a valid date string with format `YYYY-MM-DD`. - - [php] - /** @Validation({ @Date }) */ - private $birthday; - -Options: - - * message: The error message if the validation fails - -### DateTime - -Validates that a value is a valid datetime string with format `YYYY-MM-DD HH:MM:SS`. - - [php] - /** @Validation({ @DateTime }) */ - private $createdAt; - -Options: - - * message: The error message if the validation fails - -### Time - -Validates that a value is a valid time string with format `HH:MM:SS`. - - [php] - /** @Validation({ @Time }) */ - private $start; - -Options: - - * message: The error message if the validation fails - -### Email - -Validates that a value is a valid email address. - - [php] - /** @Validation({ @Email }) */ - private $email; - -Options: - - * message: The error message if the validation fails - * checkMX: Whether MX records should be checked for the domain. Default: `false` - -### File - -Validates that a value is an existing file. - - [php] - /** @Validation({ @File(maxSize="64k") }) */ - private $filename; - -Options: - - * maxSize: The maximum allowed file size. Can be provided in bytes, kilobytes - (with the suffix "k") or megabytes (with the suffix "M") - * mimeTypes: One or more allowed mime types - * notFoundMessage: The error message if the file was not found - * notReadableMessage: The error message if the file could not be read - * maxSizeMessage: The error message if `maxSize` validation fails - * mimeTypesMessage: The error message if `mimeTypes` validation fails - -### Max - -Validates that a value is at most the given limit. - - [php] - /** @Validation({ @Max(99) }) */ - private $age; - -Options: - - * limit (default): The limit - * message: The error message if validation fails - -### Min - -Works like `Max`. - -### MaxLength - -Validates that the string length of a value is at most the given limit. - - [php] - /** @Validation({ @MaxLength(32) }) */ - private $hash; - -Options: - - * limit (default): The size limit - * message: The error message if validation fails - -### MinLength - -Works like `MaxLength`. - -### Regex - -Validates that a value matches the given regular expression. - - [php] - /** @Validation({ @Regex("/\w+/") }) */ - private $title; - -Options: - - * pattern (default): The regular expression pattern - * match: Whether the pattern must be matched or must not be matched. - Default: `true` - * message: The error message if validation fails - -### Url - -Validates that a value is a valid URL. - - [php] - /** @Validation({ @Url }) */ - private $website; - -Options: - - * protocols: A list of allowed protocols. Default: "http", "https", "ftp" - and "ftps". - * message: The error message if validation fails - -Other Configuration Drivers ---------------------------- - -As always in Symfony, there are multiple ways of configuring the constraints -for your classes. Symfony supports the following four drivers. - -### XML Configuration - -The XML driver is a little verbose, but has the benefit that the XML file can be -validated to prevent errors. To use the driver, simply put a file called -`validation.xml` in the `Resources/config/` directory of your bundle. - - [xml] - - - - - - - 4 - - - - - - - - - -### YAML Configuration - -The YAML driver offers the same functionality as the XML driver. To use it, -put the file `validation.yml` in the `Resources/config/` directory of your -bundle. - - [yml] - Application\HelloBundle\Model\Author: - properties: - firstName: - - NotBlank: ~ - - MinLength: 4 - - getters: - email: - - Email: { message: "Ok, seriously now. Your email address please" } - -### PHP Configuration - -If you prefer to write configurations in plain old PHP, you can add the static -method `loadValidatorMetadata()` to the classes that you want to validate. - - [php] - use Symfony\Components\Validator\Constraints; - use Symfony\Components\Validator\Mapping\ClassMetadata; - - class Author - { - public static function loadValidatorMetadata(ClassMetadata $metadata) - { - $metadata->addPropertyConstraint('firstName', new Constraints\NotBlank()); - $metadata->addPropertyConstraint('firstName', new Constraints\MinLength(3)); - $metadata->addGetterConstraint('email', new Constraints\Email(array( - 'message' => 'Ok, seriously now. Your email address please', - ))); - } - } - -You can use either of the configuration drivers, or all together. Symfony will -merge all the information it can find. - -[1]: http://jcp.org/en/jsr/detail?id=303 diff --git a/guides/en/Validator/Constraints/AssertTrue.markdown b/guides/en/Validator/Constraints/AssertTrue.markdown new file mode 100644 index 00000000000..112a3eb7f42 --- /dev/null +++ b/guides/en/Validator/Constraints/AssertTrue.markdown @@ -0,0 +1,96 @@ +AssertTrue +========== + +Validates that a value is `true`. + + [yml] + properties: + termsAccepted: + - AssertTrue: ~ + +Options +------- + + * `message`: The error message if validation fails + + +Example 1 (YAML) +---------------- + +This constraint is very useful to execute custom validation logic. You can +put the logic in a method which returns either `true` or `false`. + +**Listing 1** + + [php] + // Application/HelloBundle/Author.php + namespace Application\HelloBundle; + + class Author + { + protected $token; + + public function isTokenValid() + { + return $this->token == $this->generateToken(); + } + } + +Then you can constrain this method with `AssertTrue`. + +**Listing 2** + + [yaml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + getters: + tokenValid: + - AssertTrue: { message: "The token is invalid" } + +If the validation of this method fails, you will see a message similar to this: + + Application\HelloBundle\Author.tokenValid: + This value should not be null + +Example 2 (XML) +--------------- + +Example 1 can also be solved using XML. + +**Listing 3** + + [xml] + + + + + + + + + +Example 3 (Docblock Annotations) +-------------------------------- + +The following listing shows how Listing 2 can be mapped using Docblock +Annotations. + +**Listing 4** + + [php] + // Application/HelloBundle/Author.php + namespace Application\HelloBundle; + + class Author + { + protected $token; + + /** + * @Validation({ @AssertTrue(message = "The token is invalid") }) + */ + public function isTokenValid() + { + return $this->token == $this->generateToken(); + } + } + diff --git a/guides/en/Validator/Constraints/Collection.markdown b/guides/en/Validator/Constraints/Collection.markdown new file mode 100644 index 00000000000..0de8607108d --- /dev/null +++ b/guides/en/Validator/Constraints/Collection.markdown @@ -0,0 +1,114 @@ +Collection +========== + +Validates array entries against different constraints. + + [yml] + - Collection: + fields: + key1: + - NotNull: ~ + key2: + - MinLength: 10 + +Options +------- + + * `fields` (required): An associative array of array keys and one or more + constraints + * `allowMissingFields`: Whether some of the keys may not be present in the + array. Default: `false` + * `allowExtraFields`: Whether the array may contain keys not present in the + `fields` option. Default: `false` + * `missingFieldsMessage`: The error message if the `allowMissingFields` + validation fails + * `allowExtraFields`: The error message if the `allowExtraFields` validation + fails + +Example 1 (YAML): +----------------- + +**Listing 1** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + options: + - Collection: + fields: + firstName: + - NotNull: ~ + lastName: + - NotNull: ~ + - MinLength: 4 + allowMissingFields: true + +The following object would fail the validation. + +**Listing 2** + + [php] + $author = new Author(); + $author->options['firstName'] = null; + $author->options['lastName'] = 'foo'; + + print $validator->validate($author); + +You should see the following error messages: + + Application\HelloBundle\Author.options[firstName]: + This value should not be null + Application\HelloBundle\Author.options[lastName]: + This value is too short. It should have 4 characters or more + +Example 2 (XML): +---------------- + +This example shows the same mapping as in Example 1 using XML. + +**Listing 3** + + [xml] + + + + + + + + + + +Example 3 (Docblock Annotations): +--------------------------------- + +This example shows the mapping from Example 1 with Docblock Annotations. + +**Listing 4** + + [php] + // Application/HelloBundle/Author.php + namespace Application\HelloBundle; + + class Author + { + /** + * @Validation({ @Collection( + * fields = { + * "firstName" = @NotNull, + * "lastName" = { @NotBlank, @MinLength(4) } + * }, + * allowMissingFields = true + * )}) + */ + private $options = array(); + } \ No newline at end of file diff --git a/guides/en/Validator/Overview.markdown b/guides/en/Validator/Overview.markdown new file mode 100644 index 00000000000..1f432104a48 --- /dev/null +++ b/guides/en/Validator/Overview.markdown @@ -0,0 +1,164 @@ +The Validator +============= + +Validation is a very common task in web applications. Data entered in forms +needs to be validated. Data also needs to be validated before it is written +into a database or passed to a web service. + +Symfony2 comes with a new Validator component that makes this task very easy. +This component is based on the [JSR303 Bean Validation specification][1]. +What? A Java specification in PHP? You heard right, but it's not as bad as it +sounds. Let's look at how we use it in PHP. + +Constraints +----------- + +The Validator is designed to validate objects against different *constraints*. +In real life, a constraint would be: "The cake must not be burned". In +Symfony2, constraints are very similar: They are assertions that a specific +condition is true. + +Constraints can be put on properties of a class, on public getters and on the +class itself. Property and getter constraints obviously can only be used to +validate a single value. Class constraints, on the other hand, can validate +the whole state of an object at once, with all its properties and methods. + +>**NOTE** +>As "getter" the validator accepts any method with the prefix "get" or "is." + +The following constraints are natively available in Symfony2: + + * [AssertFalse](Constraints/AssertFalse) + * [AssertTrue](Constraints/AssertTrue) + * [AssertType](Constraints/AssertType) + * [Choice](Constraints/Choice) + * [Collection](Constraints/Collection) + * [Date](Constraints/Date) + * [DateTime](Constraints/DateTime) + * [Email](Constraints/Email) + * [File](Constraints/File) + * [Max](Constraints/Max) + * [MaxLength](Constraints/MaxLength) + * [Min](Constraints/Min) + * [MinLength](Constraints/MinLength) + * [NotBlank](Constraints/NotBlank) + * [NotNull](Constraints/NotNull) + * [Regex](Constraints/Regex) + * [Time](Constraints/Time) + * [Url](Constraints/Url) + * [Valid](Constraints/Valid) + +Mapping +------- + +The mapping of constraints to classes, properties and getters takes place +in the mapping. Symfony2 supports YAML, XML, PHP and Docblock Annotations as +mapping drivers. + +Let's look at the YAML driver for now. We start with a simple example class +`Author`. + +**Listing 1** + + [php] + // Application/HelloBundle/Author.php + namespace Application\HelloBundle; + + class Author + { + public $firstName; + public $lastName; + + public function getFullName() + { + return $this->firstName.' '.$this->lastName; + } + } + +Now we want to put some simple constraints on this class. + + * The first and last name should not be blank + + * The first and last name together should have at least 10 characters + +To map these constraints with YAML, create a new `validation.yml` mapping file +in your bundle. + +**Listing 2** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + firstName: + - NotBlank: ~ + lastName: + - NotBlank: ~ + getters: + fullName: + - MinLength: 10 + +As you can see, the mapping is very straight-forward. + +>**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. + +This guide uses YAML mappings throughout all examples. There will be dedicated +chapters about the XML, PHP and Annotation drivers. + +The Validator +------------- + +Objects with constraints are validated by the `Validator` class. If you use +Symfony2, this class is already registered as a service in the Dependency +Injection Container. To enable the service, add the following lines to your +configuration: + +**Listing 3** + + [yml] + # config.yml + web.config: + validation: true + +Then you can get the validator from the container and start validating your +objects. + +**Listing 4** + + [php] + $validator = $container->getService('validator'); + $author = new Author(); + + print $validator->validate($author); + +The `validate()` method returns a `ConstraintViolationList` object. This object +behaves exactly like an array. You can iterate over it, and you can even print +it in a nicely formatted manner. Every element of the list corresponds to +one validation error. If the list is empty, it's time to dance, because then +validation succeeded. + +The above call will output something similar to this: + + Application\HelloBundle\Author.firstName: + This value should not be blank + Application\HelloBundle\Author.lastName: + This value should not be blank + Application\HelloBundle\Author.fullName: + This value is too short. It should have 10 characters or more + +If you fill the object with correct values, you will see that the validation +errors disappear. + +### Validating Properties + +TODO + +### Validating Values + +TODO + +[1]: http://jcp.org/en/jsr/detail?id=303 \ No newline at end of file From 97f8b470c32512392a98f4ddc0d4208670f9348e Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Sun, 4 Jul 2010 14:57:38 +0200 Subject: [PATCH 2/3] Added a dedicated page for each constraint. Started to split the validation documentation into chapters --- guides/en/Validator/Constraints.markdown | 51 ++++++ .../Constraints/AssertFalse.markdown | 17 ++ .../Validator/Constraints/AssertTrue.markdown | 2 - .../Validator/Constraints/AssertType.markdown | 33 ++++ .../en/Validator/Constraints/Choice.markdown | 153 ++++++++++++++++++ .../Validator/Constraints/Collection.markdown | 11 +- guides/en/Validator/Constraints/Date.markdown | 14 ++ .../Validator/Constraints/DateTime.markdown | 14 ++ .../en/Validator/Constraints/Email.markdown | 15 ++ guides/en/Validator/Constraints/File.markdown | 82 ++++++++++ guides/en/Validator/Constraints/Max.markdown | 15 ++ .../Validator/Constraints/MaxLength.markdown | 15 ++ guides/en/Validator/Constraints/Min.markdown | 15 ++ .../Validator/Constraints/MinLength.markdown | 15 ++ .../Validator/Constraints/NotBlank.markdown | 15 ++ .../en/Validator/Constraints/NotNull.markdown | 14 ++ .../en/Validator/Constraints/Regex.markdown | 17 ++ guides/en/Validator/Constraints/Time.markdown | 14 ++ guides/en/Validator/Constraints/Url.markdown | 16 ++ .../en/Validator/Constraints/Valid.markdown | 117 ++++++++++++++ guides/en/Validator/Mapping.markdown | 55 +++++++ guides/en/Validator/Overview.markdown | 130 +++------------ guides/en/Validator/Validation.markdown | 52 ++++++ 23 files changed, 765 insertions(+), 117 deletions(-) create mode 100644 guides/en/Validator/Constraints.markdown create mode 100644 guides/en/Validator/Constraints/AssertFalse.markdown create mode 100644 guides/en/Validator/Constraints/AssertType.markdown create mode 100644 guides/en/Validator/Constraints/Choice.markdown create mode 100644 guides/en/Validator/Constraints/Date.markdown create mode 100644 guides/en/Validator/Constraints/DateTime.markdown create mode 100644 guides/en/Validator/Constraints/Email.markdown create mode 100644 guides/en/Validator/Constraints/File.markdown create mode 100644 guides/en/Validator/Constraints/Max.markdown create mode 100644 guides/en/Validator/Constraints/MaxLength.markdown create mode 100644 guides/en/Validator/Constraints/Min.markdown create mode 100644 guides/en/Validator/Constraints/MinLength.markdown create mode 100644 guides/en/Validator/Constraints/NotBlank.markdown create mode 100644 guides/en/Validator/Constraints/NotNull.markdown create mode 100644 guides/en/Validator/Constraints/Regex.markdown create mode 100644 guides/en/Validator/Constraints/Time.markdown create mode 100644 guides/en/Validator/Constraints/Url.markdown create mode 100644 guides/en/Validator/Constraints/Valid.markdown create mode 100644 guides/en/Validator/Mapping.markdown create mode 100644 guides/en/Validator/Validation.markdown diff --git a/guides/en/Validator/Constraints.markdown b/guides/en/Validator/Constraints.markdown new file mode 100644 index 00000000000..64b55c4b34d --- /dev/null +++ b/guides/en/Validator/Constraints.markdown @@ -0,0 +1,51 @@ +Constraints +=========== + +The Validator is designed to validate objects against different *constraints*. +In real life, a constraint would be: "The cake must not be burned". In +Symfony2, constraints are very similar: They are assertions that a specific +condition is true. + +Constraints can be put on properties of a class, on public getters and on the +class itself. Property and getter constraints obviously can only be used to +validate a single value. Class constraints, on the other hand, can validate +the whole state of an object at once, with all its properties and methods. + +>**NOTE** +>As "getter" the validator accepts any method with the prefix "get" or "is." + +Supported Constraints +--------------------- + +The following constraints are natively available in Symfony2: + + * [AssertFalse](Constraints/AssertFalse) + * [AssertTrue](Constraints/AssertTrue) + * [AssertType](Constraints/AssertType) + * [Choice](Constraints/Choice) + * [Collection](Constraints/Collection) + * [Date](Constraints/Date) + * [DateTime](Constraints/DateTime) + * [Email](Constraints/Email) + * [File](Constraints/File) + * [Max](Constraints/Max) + * [MaxLength](Constraints/MaxLength) + * [Min](Constraints/Min) + * [MinLength](Constraints/MinLength) + * [NotBlank](Constraints/NotBlank) + * [NotNull](Constraints/NotNull) + * [Regex](Constraints/Regex) + * [Time](Constraints/Time) + * [Url](Constraints/Url) + * [Valid](Constraints/Valid) + +Constraint Options +------------------ + +TODO + + + + + + diff --git a/guides/en/Validator/Constraints/AssertFalse.markdown b/guides/en/Validator/Constraints/AssertFalse.markdown new file mode 100644 index 00000000000..2d3709ea8ee --- /dev/null +++ b/guides/en/Validator/Constraints/AssertFalse.markdown @@ -0,0 +1,17 @@ +AssertTrue +========== + +Validates that a value is `false`. + + [yml] + properties: + deleted: + - AssertFalse: ~ + +Options +------- + + * `message`: The error message if validation fails + + +See [AssertFalse](AssertFalse). \ No newline at end of file diff --git a/guides/en/Validator/Constraints/AssertTrue.markdown b/guides/en/Validator/Constraints/AssertTrue.markdown index 112a3eb7f42..c5e967a93c6 100644 --- a/guides/en/Validator/Constraints/AssertTrue.markdown +++ b/guides/en/Validator/Constraints/AssertTrue.markdown @@ -24,8 +24,6 @@ put the logic in a method which returns either `true` or `false`. [php] // Application/HelloBundle/Author.php - namespace Application\HelloBundle; - class Author { protected $token; diff --git a/guides/en/Validator/Constraints/AssertType.markdown b/guides/en/Validator/Constraints/AssertType.markdown new file mode 100644 index 00000000000..d2430d952ec --- /dev/null +++ b/guides/en/Validator/Constraints/AssertType.markdown @@ -0,0 +1,33 @@ +AssertType +========== + +Validates that a value has a specific data type + + [yml] + properties: + age: + - AssertType: integer + +Options +------- + + * `type` (**default**, required): A fully qualified class name or one of the + PHP datatypes as determined by PHP's `is_` functions. + + * [`array`](http://php.net/is_array) + * [`bool`](http://php.net/is_bool) + * [`callable`](http://php.net/is_callable) + * [`float`](http://php.net/is_float) + * [`double`](http://php.net/is_double) + * [`int`](http://php.net/is_int) + * [`integer`](http://php.net/is_integer) + * [`long`](http://php.net/is_long) + * [`null`](http://php.net/is_null) + * [`numeric`](http://php.net/is_numeric) + * [`object`](http://php.net/is_object) + * [`real`](http://php.net/is_real) + * [`resource`](http://php.net/is_resource) + * [`scalar`](http://php.net/is_scalar) + * [`string`](http://php.net/is_string) + + * `message`: The error message in case the validation fails diff --git a/guides/en/Validator/Constraints/Choice.markdown b/guides/en/Validator/Constraints/Choice.markdown new file mode 100644 index 00000000000..04a639826b0 --- /dev/null +++ b/guides/en/Validator/Constraints/Choice.markdown @@ -0,0 +1,153 @@ +Choice +====== + +Validates that a value is one or more of a list of choices. + + [yml] + properties: + gender: + - Choice: [male, female] + +Options +------- + + * `choices` (**default**, required): The available choices + * `callback`: Can be used instead of `choices`. A static callback method + returning the choices. If you pass a string, it is expected to be + the name of a static method in the validated class. + * `multiple`: Whether multiple choices are allowed. Default: `false` + * `min`: The minimum amount of selected choices + * `max`: The maximum amount of selected choices + * `message`: The error message if validation fails + * `minMessage`: The error message if `min` validation fails + * `maxMessage`: The error message if `max` validation fails + +Example 1: Choices as array (YAML) +---------------------------------- + +If the choices are few and easy to determine, they can be passed to the +constraint definition as array. + +**Listing 1** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + gender: + - Choice: [male, female] + +Example 2: Choices as array (XML) +--------------------------------- + +The following snippet shows the mapping of Example 1 using XML. + +**Listing 2** + + [xml] + + + + + male + female + + + + +Example 3: Choices as array (Docblock Annotations) +-------------------------------------------------- + +Of course, Example 1 can also be solved with annotations. + +**Listing 3** + + [php] + // Application/HelloBundle/Author.php + class Author + { + /** + * @Validation({ @Choice({"male", "female"}) }) + */ + protected $gender; + } + +Example 4: Choices from a callback (YAML) +----------------------------------------- + +When you also need the choices in other contexts (such as a drop-down box in +a form), it is more flexible to bind them to your domain model using a static +callback method. + +**Listing 4** + + [php] + // Application/HelloBundle/Author.php + class Author + { + public static function getGenders() + { + return array('male', 'female'); + } + } + +You can pass the name of this method to the `callback` option of the `Choice` +constraint. + +**Listing 5** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + gender: + - Choice: { callback: getGenders } + +If the static callback is stored in a different class, for example `Util`, +you can pass the class name and the method as array. + +**Listing 6** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + gender: + - Choice: { callback: [Util, getGenders] } + +Example 5: Choices from a callback (XML) +---------------------------------------- + +The following listing shows how Listing 6 is written with XML. + +**Listing 7** + + [xml] + + + + + + + + + +Example 6: Choices from a callback (Docblock Annotations) +--------------------------------------------------------- + +Here you see how the mapping of Listing 6 is written with annotations. + +**Listing 8** + + [php] + // Application/HelloBundle/Author.php + class Author + { + /** + * @Validation({ @Choice(callback = {"Util", "getGenders"}) }) + */ + protected $gender; + } diff --git a/guides/en/Validator/Constraints/Collection.markdown b/guides/en/Validator/Constraints/Collection.markdown index 0de8607108d..832f1e549a1 100644 --- a/guides/en/Validator/Constraints/Collection.markdown +++ b/guides/en/Validator/Constraints/Collection.markdown @@ -28,6 +28,11 @@ Options Example 1 (YAML): ----------------- +Let's validate an array with two indexes `firstName` and `lastName`. The value +of `firstName` must not be blank, while the value of `lastName` must not be +blank with a minimum length of four characters. Furthermore, both keys +may not exist in the array. + **Listing 1** [yml] @@ -38,9 +43,9 @@ Example 1 (YAML): - Collection: fields: firstName: - - NotNull: ~ + - NotBlank: ~ lastName: - - NotNull: ~ + - NotBlank: ~ - MinLength: 4 allowMissingFields: true @@ -97,8 +102,6 @@ This example shows the mapping from Example 1 with Docblock Annotations. [php] // Application/HelloBundle/Author.php - namespace Application\HelloBundle; - class Author { /** diff --git a/guides/en/Validator/Constraints/Date.markdown b/guides/en/Validator/Constraints/Date.markdown new file mode 100644 index 00000000000..0e6f4961f36 --- /dev/null +++ b/guides/en/Validator/Constraints/Date.markdown @@ -0,0 +1,14 @@ +Date +==== + +Validates that a value is a valid date string with format "YYYY-MM-DD". + + [yml] + properties: + birthday: + - Date: ~ + +Options +------- + + * `message`: The error message if the validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/DateTime.markdown b/guides/en/Validator/Constraints/DateTime.markdown new file mode 100644 index 00000000000..2ecc3597ca6 --- /dev/null +++ b/guides/en/Validator/Constraints/DateTime.markdown @@ -0,0 +1,14 @@ +DateTime +======== + +Validates that a value is a valid datetime string with format "YYYY-MM-DD HH:MM:SS". + + [yml] + properties: + createdAt: + - DateTime: ~ + +Options +------- + + * `message`: The error message if the validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Email.markdown b/guides/en/Validator/Constraints/Email.markdown new file mode 100644 index 00000000000..59c9b06b8b5 --- /dev/null +++ b/guides/en/Validator/Constraints/Email.markdown @@ -0,0 +1,15 @@ +Email +===== + +Validates that a value is a valid email address. + + [yml] + properties: + email: + - Email: ~ + +Options +------- + + * `checkMX`: Whether MX records should be checked for the domain. Default: `false` + * `message`: The error message if the validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/File.markdown b/guides/en/Validator/Constraints/File.markdown new file mode 100644 index 00000000000..7acc45f20ee --- /dev/null +++ b/guides/en/Validator/Constraints/File.markdown @@ -0,0 +1,82 @@ +File +==== + +Validates that a value is the path to an existing file. + + [yml] + properties: + filename: + - File: ~ + +Options +------- + + * `maxSize`: The maximum allowed file size. Can be provided in bytes, kilobytes + (with the suffix "k") or megabytes (with the suffix "M") + * `mimeTypes`: One or more allowed mime types + * `notFoundMessage`: The error message if the file was not found + * `notReadableMessage`: The error message if the file could not be read + * `maxSizeMessage`: The error message if `maxSize` validation fails + * `mimeTypesMessage`: The error message if `mimeTypes` validation fails + +Example 1: Validating the file size and mime type (YAML) +-------------------------------------------------------- + +In this example we use the `File` constraint to verify that the file does +not exceed a maximum size of 128 kilobytes and is a PDF document. + +**Listing 1** + + [yml] + properties: + filename: + - File: { maxSize: 128k, mimeTypes: [application/pdf, application/x-pdf] } + +When you validate the object with a file that doesn't satisfy one of these +constraints, a proper error message is returned by the validator. + + Application\HelloBundle\Author.filename: + The file is too large (150 kB). Allowed maximum size is 128 kB + +Example 2: Validating the file size and mime type (XML) +------------------------------------------------------- + +This listing shows the example of Listing 1 using XML. + +**Listing 2** + + [xml] + + + + + + + + + + +Example 3: Validating the file size and mime type (Docblock Annotations) +------------------------------------------------------------------------ + +As always it is possible to map Listing 1 with annotations, too. + +**Listing 3** + + [php] + // Application/HelloBundle/Author.php + class Author + { + /** + * @Validation({ + * @File(maxSize = "128k", mimeTypes = { + * "application/pdf", + * "application/x-pdf" + * }) + * }) + */ + private $filename; + } diff --git a/guides/en/Validator/Constraints/Max.markdown b/guides/en/Validator/Constraints/Max.markdown new file mode 100644 index 00000000000..778abffbdc7 --- /dev/null +++ b/guides/en/Validator/Constraints/Max.markdown @@ -0,0 +1,15 @@ +Max +=== + +Validates that a value is not greater than the given limit. + + [yml] + properties: + age: + - Max: 99 + +Options +------- + + * `limit` (**default**, required): The limit + * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/MaxLength.markdown b/guides/en/Validator/Constraints/MaxLength.markdown new file mode 100644 index 00000000000..2c19397f125 --- /dev/null +++ b/guides/en/Validator/Constraints/MaxLength.markdown @@ -0,0 +1,15 @@ +MaxLength +========= + +Validates that the string length of a value is not greater than the given limit. + + [yml] + properties: + firstName: + - MaxLength: 20 + +Options +------- + + * `limit` (**default**, required): The limit + * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Min.markdown b/guides/en/Validator/Constraints/Min.markdown new file mode 100644 index 00000000000..0295fbbb859 --- /dev/null +++ b/guides/en/Validator/Constraints/Min.markdown @@ -0,0 +1,15 @@ +Min +=== + +Validates that a value is not smaller than the given limit. + + [yml] + properties: + age: + - Min: 1 + +Options +------- + + * `limit` (**default**, required): The limit + * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/MinLength.markdown b/guides/en/Validator/Constraints/MinLength.markdown new file mode 100644 index 00000000000..64bcd59019d --- /dev/null +++ b/guides/en/Validator/Constraints/MinLength.markdown @@ -0,0 +1,15 @@ +MinLength +========= + +Validates that the string length of a value is not smaller than the given limit. + + [yml] + properties: + firstName: + - MinLength: 3 + +Options +------- + + * `limit` (**default**, required): The limit + * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/NotBlank.markdown b/guides/en/Validator/Constraints/NotBlank.markdown new file mode 100644 index 00000000000..2c73d3a6cb6 --- /dev/null +++ b/guides/en/Validator/Constraints/NotBlank.markdown @@ -0,0 +1,15 @@ +NotBlank +======== + +Validates that a value is not empty (as determined by the +[`empty`](http://php.net/empty) construct). + + [yml] + properties: + firstName: + - NotBlank: ~ + +Options +------- + + * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/NotNull.markdown b/guides/en/Validator/Constraints/NotNull.markdown new file mode 100644 index 00000000000..392698a71d6 --- /dev/null +++ b/guides/en/Validator/Constraints/NotNull.markdown @@ -0,0 +1,14 @@ +NotNull +======= + +Validates that a value is not `null`. + + [yml] + properties: + firstName: + - NotNull: ~ + +Options +------- + + * `message`: The error message if validation fails diff --git a/guides/en/Validator/Constraints/Regex.markdown b/guides/en/Validator/Constraints/Regex.markdown new file mode 100644 index 00000000000..8258a0ae53c --- /dev/null +++ b/guides/en/Validator/Constraints/Regex.markdown @@ -0,0 +1,17 @@ +Regex +===== + +Validates that a value matches a regular expression. + + [yml] + properties: + title: + - Regex: /\w+/ + +Options +------- + + * `pattern` (**default**, required): The regular expression pattern + * `match`: Whether the pattern must be matched or must not be matched. + Default: `true` + * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Time.markdown b/guides/en/Validator/Constraints/Time.markdown new file mode 100644 index 00000000000..b1beda39305 --- /dev/null +++ b/guides/en/Validator/Constraints/Time.markdown @@ -0,0 +1,14 @@ +Time +==== + +Validates that a value is a valid time string with format "HH:MM:SS". + + [yml] + properties: + createdAt: + - DateTime: ~ + +Options +------- + + * `message`: The error message if the validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Url.markdown b/guides/en/Validator/Constraints/Url.markdown new file mode 100644 index 00000000000..80f4a59f01b --- /dev/null +++ b/guides/en/Validator/Constraints/Url.markdown @@ -0,0 +1,16 @@ +Url +=== + +Validates that a value is a valid URL string. + + [yml] + properties: + website: + - Url: ~ + +Options +------- + + * `protocols`: A list of allowed protocols. Default: "http", "https", "ftp" + and "ftps". + * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Valid.markdown b/guides/en/Validator/Constraints/Valid.markdown new file mode 100644 index 00000000000..5568b8151bc --- /dev/null +++ b/guides/en/Validator/Constraints/Valid.markdown @@ -0,0 +1,117 @@ +Valid +===== + +Validates an associated object. + + [yml] + properties: + address: + - Valid: ~ + +Options +------- + + * `class`: The expected class of the object + * `message`: The error message if the class doesn't match + +Example 1: Validate object trees (YAML) +--------------------------------------- + +This constraint helps to validate whole object trees. In the following example, +we create two classes `Author` and `Address` that both have constraints on +their properties. Furthermore, `Author` stores an `Address` instance in the +`$address` property. + +**Listing 1** + + [php] + // Application/HelloBundle/Address.php + class Address + { + protected $street; + protected $zipCode; + } + +**Listing 2** + + [php] + // Application/HelloBundle/Author.php + class Author + { + protected $firstName; + protected $lastName; + protected $address; + } + +**Listing 3** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Address: + properties: + street: + - NotBlank: ~ + zipCode: + - NotBlank: ~ + - MaxLength: 5 + + Application\HelloBundle\Author: + properties: + firstName: + - NotBlank: ~ + - MinLength: 4 + lastName: + - NotBlank: ~ + +With this mapping it is possible to successfully validate an author with an +invalid address. To prevent that, we add the `Valid` constraint to the +`$address` property. + +**Listing 4** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + address: + - Valid: ~ + +We can even go one step further and validate the class of the related object +to be `Address` or one of its subclasses. + +**Listing 5** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + address: + - Valid: { class: Application\ḨelloBundle\Address } + +Example 2: Validate object trees (XML) +-------------------------------------- + +The following code snippet shows the mapping of Listing 5 in XML. + + [xml] + + + + Application\HelloBundle\Address + + + +Example 3: Validate object trees (Docblock Annotations) +------------------------------------------------------- + +With annotations, the mapping of Listing 5 looks like this: + + [php] + // Application/HelloBundle/Author.php + class Author + { + /** + * @Validation({ @Valid(class = "Application\HelloBundle\Address") }) + */ + protected $address; + } diff --git a/guides/en/Validator/Mapping.markdown b/guides/en/Validator/Mapping.markdown new file mode 100644 index 00000000000..7277815bbeb --- /dev/null +++ b/guides/en/Validator/Mapping.markdown @@ -0,0 +1,55 @@ +Constraint Mapping +================== + +The mapping of constraints to classes, properties and getters takes place +in the mapping. Symfony2 supports YAML, XML, PHP and Docblock Annotations as +mapping drivers. + +Let's look at the YAML driver for now. We start with a simple example class +`Author`. + +**Listing 1** + + [php] + // Application/HelloBundle/Author.php + class Author + { + public $firstName; + public $lastName; + + public function getFullName() + { + return $this->firstName.' '.$this->lastName; + } + } + +Now we want to put some simple constraints on this class. + + * The first and last name should not be blank + + * The first and last name together should have at least 10 characters + +To map these constraints with YAML, create a new `validation.yml` mapping file +in your bundle. + +**Listing 2** + + [yml] + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + firstName: + - NotBlank: ~ + lastName: + - NotBlank: ~ + getters: + fullName: + - MinLength: 10 + +As you can see, the mapping is very straight-forward. + +>**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. \ No newline at end of file diff --git a/guides/en/Validator/Overview.markdown b/guides/en/Validator/Overview.markdown index 1f432104a48..285d4b5b4ec 100644 --- a/guides/en/Validator/Overview.markdown +++ b/guides/en/Validator/Overview.markdown @@ -10,122 +10,48 @@ This component is based on the [JSR303 Bean Validation specification][1]. What? A Java specification in PHP? You heard right, but it's not as bad as it sounds. Let's look at how we use it in PHP. -Constraints ------------ - -The Validator is designed to validate objects against different *constraints*. -In real life, a constraint would be: "The cake must not be burned". In -Symfony2, constraints are very similar: They are assertions that a specific -condition is true. - -Constraints can be put on properties of a class, on public getters and on the -class itself. Property and getter constraints obviously can only be used to -validate a single value. Class constraints, on the other hand, can validate -the whole state of an object at once, with all its properties and methods. - ->**NOTE** ->As "getter" the validator accepts any method with the prefix "get" or "is." - -The following constraints are natively available in Symfony2: - - * [AssertFalse](Constraints/AssertFalse) - * [AssertTrue](Constraints/AssertTrue) - * [AssertType](Constraints/AssertType) - * [Choice](Constraints/Choice) - * [Collection](Constraints/Collection) - * [Date](Constraints/Date) - * [DateTime](Constraints/DateTime) - * [Email](Constraints/Email) - * [File](Constraints/File) - * [Max](Constraints/Max) - * [MaxLength](Constraints/MaxLength) - * [Min](Constraints/Min) - * [MinLength](Constraints/MinLength) - * [NotBlank](Constraints/NotBlank) - * [NotNull](Constraints/NotNull) - * [Regex](Constraints/Regex) - * [Time](Constraints/Time) - * [Url](Constraints/Url) - * [Valid](Constraints/Valid) - -Mapping +Example ------- -The mapping of constraints to classes, properties and getters takes place -in the mapping. Symfony2 supports YAML, XML, PHP and Docblock Annotations as -mapping drivers. - -Let's look at the YAML driver for now. We start with a simple example class -`Author`. +The validator validates objects against [constraints](Constraints). Let's start +with the simple constraint that the `$name` property of a class `Author` must +not be empty. **Listing 1** [php] // Application/HelloBundle/Author.php - namespace Application\HelloBundle; - class Author { - public $firstName; - public $lastName; - - public function getFullName() - { - return $this->firstName.' '.$this->lastName; - } + private $name; } -Now we want to put some simple constraints on this class. - - * The first and last name should not be blank - - * The first and last name together should have at least 10 characters - -To map these constraints with YAML, create a new `validation.yml` mapping file -in your bundle. - **Listing 2** [yml] # Application/HelloBundle/Resources/config/validation.yml Application\HelloBundle\Author: properties: - firstName: + name: - NotBlank: ~ - lastName: - - NotBlank: ~ - getters: - fullName: - - MinLength: 10 -As you can see, the mapping is very straight-forward. - ->**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. - -This guide uses YAML mappings throughout all examples. There will be dedicated -chapters about the XML, PHP and Annotation drivers. +Listing 2 shows a YAML file that connects properties of the class with +constraints. This process is called the [mapping](Mapping). -The Validator -------------- - -Objects with constraints are validated by the `Validator` class. If you use -Symfony2, this class is already registered as a service in the Dependency -Injection Container. To enable the service, add the following lines to your -configuration: +Finally, we can use the `Validator` class for [validation](Validation). Symfony2 +provides a validator instance as a service in the Dependency Injection +Container. To use that service, adapt your application configuration. **Listing 3** [yml] # config.yml web.config: - validation: true + validation: + enabled: true -Then you can get the validator from the container and start validating your -objects. +Now call the `validate()` method on the service, which delivers a list of +errors if validation fails. **Listing 4** @@ -135,30 +61,12 @@ objects. print $validator->validate($author); -The `validate()` method returns a `ConstraintViolationList` object. This object -behaves exactly like an array. You can iterate over it, and you can even print -it in a nicely formatted manner. Every element of the list corresponds to -one validation error. If the list is empty, it's time to dance, because then -validation succeeded. - -The above call will output something similar to this: +Because the `$name` property is empty, you will see the following error +message. - Application\HelloBundle\Author.firstName: + Application\HelloBundle\Author.name: This value should not be blank - Application\HelloBundle\Author.lastName: - This value should not be blank - Application\HelloBundle\Author.fullName: - This value is too short. It should have 10 characters or more -If you fill the object with correct values, you will see that the validation -errors disappear. - -### Validating Properties - -TODO - -### Validating Values - -TODO +Insert a value into the property and the error message will disappear. [1]: http://jcp.org/en/jsr/detail?id=303 \ No newline at end of file diff --git a/guides/en/Validator/Validation.markdown b/guides/en/Validator/Validation.markdown new file mode 100644 index 00000000000..831a6a13636 --- /dev/null +++ b/guides/en/Validator/Validation.markdown @@ -0,0 +1,52 @@ +Constraint Validation +===================== + +Objects with constraints are validated by the `Validator` class. If you use +Symfony2, this class is already registered as a service in the Dependency +Injection Container. To enable the service, add the following lines to your +configuration: + +**Listing 1** + + [yml] + # config.yml + web.config: + validation: + enabled: true + +Then you can get the validator from the container and start validating your +objects. + +**Listing 2** + + [php] + $validator = $container->getService('validator'); + $author = new Author(); + + print $validator->validate($author); + +The `validate()` method returns a `ConstraintViolationList` object. This object +behaves exactly like an array. You can iterate over it, and you can even print +it in a nicely formatted manner. Every element of the list corresponds to +one validation error. If the list is empty, it's time to dance, because then +validation succeeded. + +The above call will output something similar to this: + + Application\HelloBundle\Author.firstName: + This value should not be blank + Application\HelloBundle\Author.lastName: + This value should not be blank + Application\HelloBundle\Author.fullName: + This value is too short. It should have 10 characters or more + +If you fill the object with correct values, you will see that the validation +errors disappear. + +### Validating Properties + +TODO + +### Validating Values + +TODO \ No newline at end of file From 0973f5d48299adc611bf7b8f0d99b26a9c7fb4d2 Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Fri, 12 Nov 2010 07:17:53 +0100 Subject: [PATCH 3/3] Added more extensive validation documentation --- guides/en/Validator/Constraints.markdown | 51 -- .../Constraints/AssertFalse.markdown | 17 - .../Validator/Constraints/AssertTrue.markdown | 94 ---- .../Validator/Constraints/AssertType.markdown | 33 -- .../en/Validator/Constraints/Choice.markdown | 153 ------ .../Validator/Constraints/Collection.markdown | 117 ---- .../en/Validator/Constraints/Email.markdown | 15 - guides/en/Validator/Constraints/File.markdown | 82 --- guides/en/Validator/Constraints/Max.markdown | 15 - .../Validator/Constraints/MaxLength.markdown | 15 - guides/en/Validator/Constraints/Min.markdown | 15 - .../Validator/Constraints/MinLength.markdown | 15 - .../Validator/Constraints/NotBlank.markdown | 15 - .../en/Validator/Constraints/NotNull.markdown | 14 - .../en/Validator/Constraints/Regex.markdown | 17 - guides/en/Validator/Constraints/Time.markdown | 14 - guides/en/Validator/Constraints/Url.markdown | 16 - .../en/Validator/Constraints/Valid.markdown | 117 ---- guides/en/Validator/Mapping.markdown | 55 -- guides/en/Validator/Overview.markdown | 72 --- guides/validation.rst | 498 ------------------ guides/validator/constraints.markdown | 218 ++++++++ guides/validator/constraints/AssertFalse.rst | 18 + guides/validator/constraints/AssertTrue.rst | 83 +++ guides/validator/constraints/AssertType.rst | 34 ++ guides/validator/constraints/Choice.rst | 154 ++++++ guides/validator/constraints/Collection.rst | 109 ++++ .../constraints/Date.rst} | 9 +- .../constraints/DateTime.rst} | 9 +- guides/validator/constraints/Email.rst | 16 + guides/validator/constraints/File.rst | 73 +++ guides/validator/constraints/Max.rst | 16 + guides/validator/constraints/MaxLength.rst | 16 + guides/validator/constraints/Min.rst | 16 + guides/validator/constraints/MinLength.rst | 16 + guides/validator/constraints/NotBlank.rst | 16 + guides/validator/constraints/NotNull.rst | 15 + guides/validator/constraints/Regex.rst | 18 + guides/validator/constraints/Time.rst | 15 + guides/validator/constraints/Url.rst | 17 + guides/validator/constraints/Valid.rst | 186 +++++++ guides/validator/index.rst | 9 + guides/validator/overview.markdown | 89 ++++ .../validation.markdown} | 35 +- 44 files changed, 1158 insertions(+), 1469 deletions(-) delete mode 100644 guides/en/Validator/Constraints.markdown delete mode 100644 guides/en/Validator/Constraints/AssertFalse.markdown delete mode 100644 guides/en/Validator/Constraints/AssertTrue.markdown delete mode 100644 guides/en/Validator/Constraints/AssertType.markdown delete mode 100644 guides/en/Validator/Constraints/Choice.markdown delete mode 100644 guides/en/Validator/Constraints/Collection.markdown delete mode 100644 guides/en/Validator/Constraints/Email.markdown delete mode 100644 guides/en/Validator/Constraints/File.markdown delete mode 100644 guides/en/Validator/Constraints/Max.markdown delete mode 100644 guides/en/Validator/Constraints/MaxLength.markdown delete mode 100644 guides/en/Validator/Constraints/Min.markdown delete mode 100644 guides/en/Validator/Constraints/MinLength.markdown delete mode 100644 guides/en/Validator/Constraints/NotBlank.markdown delete mode 100644 guides/en/Validator/Constraints/NotNull.markdown delete mode 100644 guides/en/Validator/Constraints/Regex.markdown delete mode 100644 guides/en/Validator/Constraints/Time.markdown delete mode 100644 guides/en/Validator/Constraints/Url.markdown delete mode 100644 guides/en/Validator/Constraints/Valid.markdown delete mode 100644 guides/en/Validator/Mapping.markdown delete mode 100644 guides/en/Validator/Overview.markdown delete mode 100644 guides/validation.rst create mode 100644 guides/validator/constraints.markdown create mode 100644 guides/validator/constraints/AssertFalse.rst create mode 100644 guides/validator/constraints/AssertTrue.rst create mode 100644 guides/validator/constraints/AssertType.rst create mode 100644 guides/validator/constraints/Choice.rst create mode 100644 guides/validator/constraints/Collection.rst rename guides/{en/Validator/Constraints/Date.markdown => validator/constraints/Date.rst} (51%) rename guides/{en/Validator/Constraints/DateTime.markdown => validator/constraints/DateTime.rst} (53%) create mode 100644 guides/validator/constraints/Email.rst create mode 100644 guides/validator/constraints/File.rst create mode 100644 guides/validator/constraints/Max.rst create mode 100644 guides/validator/constraints/MaxLength.rst create mode 100644 guides/validator/constraints/Min.rst create mode 100644 guides/validator/constraints/MinLength.rst create mode 100644 guides/validator/constraints/NotBlank.rst create mode 100644 guides/validator/constraints/NotNull.rst create mode 100644 guides/validator/constraints/Regex.rst create mode 100644 guides/validator/constraints/Time.rst create mode 100644 guides/validator/constraints/Url.rst create mode 100644 guides/validator/constraints/Valid.rst create mode 100644 guides/validator/index.rst create mode 100644 guides/validator/overview.markdown rename guides/{en/Validator/Validation.markdown => validator/validation.markdown} (64%) diff --git a/guides/en/Validator/Constraints.markdown b/guides/en/Validator/Constraints.markdown deleted file mode 100644 index 64b55c4b34d..00000000000 --- a/guides/en/Validator/Constraints.markdown +++ /dev/null @@ -1,51 +0,0 @@ -Constraints -=========== - -The Validator is designed to validate objects against different *constraints*. -In real life, a constraint would be: "The cake must not be burned". In -Symfony2, constraints are very similar: They are assertions that a specific -condition is true. - -Constraints can be put on properties of a class, on public getters and on the -class itself. Property and getter constraints obviously can only be used to -validate a single value. Class constraints, on the other hand, can validate -the whole state of an object at once, with all its properties and methods. - ->**NOTE** ->As "getter" the validator accepts any method with the prefix "get" or "is." - -Supported Constraints ---------------------- - -The following constraints are natively available in Symfony2: - - * [AssertFalse](Constraints/AssertFalse) - * [AssertTrue](Constraints/AssertTrue) - * [AssertType](Constraints/AssertType) - * [Choice](Constraints/Choice) - * [Collection](Constraints/Collection) - * [Date](Constraints/Date) - * [DateTime](Constraints/DateTime) - * [Email](Constraints/Email) - * [File](Constraints/File) - * [Max](Constraints/Max) - * [MaxLength](Constraints/MaxLength) - * [Min](Constraints/Min) - * [MinLength](Constraints/MinLength) - * [NotBlank](Constraints/NotBlank) - * [NotNull](Constraints/NotNull) - * [Regex](Constraints/Regex) - * [Time](Constraints/Time) - * [Url](Constraints/Url) - * [Valid](Constraints/Valid) - -Constraint Options ------------------- - -TODO - - - - - - diff --git a/guides/en/Validator/Constraints/AssertFalse.markdown b/guides/en/Validator/Constraints/AssertFalse.markdown deleted file mode 100644 index 2d3709ea8ee..00000000000 --- a/guides/en/Validator/Constraints/AssertFalse.markdown +++ /dev/null @@ -1,17 +0,0 @@ -AssertTrue -========== - -Validates that a value is `false`. - - [yml] - properties: - deleted: - - AssertFalse: ~ - -Options -------- - - * `message`: The error message if validation fails - - -See [AssertFalse](AssertFalse). \ No newline at end of file diff --git a/guides/en/Validator/Constraints/AssertTrue.markdown b/guides/en/Validator/Constraints/AssertTrue.markdown deleted file mode 100644 index c5e967a93c6..00000000000 --- a/guides/en/Validator/Constraints/AssertTrue.markdown +++ /dev/null @@ -1,94 +0,0 @@ -AssertTrue -========== - -Validates that a value is `true`. - - [yml] - properties: - termsAccepted: - - AssertTrue: ~ - -Options -------- - - * `message`: The error message if validation fails - - -Example 1 (YAML) ----------------- - -This constraint is very useful to execute custom validation logic. You can -put the logic in a method which returns either `true` or `false`. - -**Listing 1** - - [php] - // Application/HelloBundle/Author.php - class Author - { - protected $token; - - public function isTokenValid() - { - return $this->token == $this->generateToken(); - } - } - -Then you can constrain this method with `AssertTrue`. - -**Listing 2** - - [yaml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - getters: - tokenValid: - - AssertTrue: { message: "The token is invalid" } - -If the validation of this method fails, you will see a message similar to this: - - Application\HelloBundle\Author.tokenValid: - This value should not be null - -Example 2 (XML) ---------------- - -Example 1 can also be solved using XML. - -**Listing 3** - - [xml] - - - - - - - - - -Example 3 (Docblock Annotations) --------------------------------- - -The following listing shows how Listing 2 can be mapped using Docblock -Annotations. - -**Listing 4** - - [php] - // Application/HelloBundle/Author.php - namespace Application\HelloBundle; - - class Author - { - protected $token; - - /** - * @Validation({ @AssertTrue(message = "The token is invalid") }) - */ - public function isTokenValid() - { - return $this->token == $this->generateToken(); - } - } - diff --git a/guides/en/Validator/Constraints/AssertType.markdown b/guides/en/Validator/Constraints/AssertType.markdown deleted file mode 100644 index d2430d952ec..00000000000 --- a/guides/en/Validator/Constraints/AssertType.markdown +++ /dev/null @@ -1,33 +0,0 @@ -AssertType -========== - -Validates that a value has a specific data type - - [yml] - properties: - age: - - AssertType: integer - -Options -------- - - * `type` (**default**, required): A fully qualified class name or one of the - PHP datatypes as determined by PHP's `is_` functions. - - * [`array`](http://php.net/is_array) - * [`bool`](http://php.net/is_bool) - * [`callable`](http://php.net/is_callable) - * [`float`](http://php.net/is_float) - * [`double`](http://php.net/is_double) - * [`int`](http://php.net/is_int) - * [`integer`](http://php.net/is_integer) - * [`long`](http://php.net/is_long) - * [`null`](http://php.net/is_null) - * [`numeric`](http://php.net/is_numeric) - * [`object`](http://php.net/is_object) - * [`real`](http://php.net/is_real) - * [`resource`](http://php.net/is_resource) - * [`scalar`](http://php.net/is_scalar) - * [`string`](http://php.net/is_string) - - * `message`: The error message in case the validation fails diff --git a/guides/en/Validator/Constraints/Choice.markdown b/guides/en/Validator/Constraints/Choice.markdown deleted file mode 100644 index 04a639826b0..00000000000 --- a/guides/en/Validator/Constraints/Choice.markdown +++ /dev/null @@ -1,153 +0,0 @@ -Choice -====== - -Validates that a value is one or more of a list of choices. - - [yml] - properties: - gender: - - Choice: [male, female] - -Options -------- - - * `choices` (**default**, required): The available choices - * `callback`: Can be used instead of `choices`. A static callback method - returning the choices. If you pass a string, it is expected to be - the name of a static method in the validated class. - * `multiple`: Whether multiple choices are allowed. Default: `false` - * `min`: The minimum amount of selected choices - * `max`: The maximum amount of selected choices - * `message`: The error message if validation fails - * `minMessage`: The error message if `min` validation fails - * `maxMessage`: The error message if `max` validation fails - -Example 1: Choices as array (YAML) ----------------------------------- - -If the choices are few and easy to determine, they can be passed to the -constraint definition as array. - -**Listing 1** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - gender: - - Choice: [male, female] - -Example 2: Choices as array (XML) ---------------------------------- - -The following snippet shows the mapping of Example 1 using XML. - -**Listing 2** - - [xml] - - - - - male - female - - - - -Example 3: Choices as array (Docblock Annotations) --------------------------------------------------- - -Of course, Example 1 can also be solved with annotations. - -**Listing 3** - - [php] - // Application/HelloBundle/Author.php - class Author - { - /** - * @Validation({ @Choice({"male", "female"}) }) - */ - protected $gender; - } - -Example 4: Choices from a callback (YAML) ------------------------------------------ - -When you also need the choices in other contexts (such as a drop-down box in -a form), it is more flexible to bind them to your domain model using a static -callback method. - -**Listing 4** - - [php] - // Application/HelloBundle/Author.php - class Author - { - public static function getGenders() - { - return array('male', 'female'); - } - } - -You can pass the name of this method to the `callback` option of the `Choice` -constraint. - -**Listing 5** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - gender: - - Choice: { callback: getGenders } - -If the static callback is stored in a different class, for example `Util`, -you can pass the class name and the method as array. - -**Listing 6** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - gender: - - Choice: { callback: [Util, getGenders] } - -Example 5: Choices from a callback (XML) ----------------------------------------- - -The following listing shows how Listing 6 is written with XML. - -**Listing 7** - - [xml] - - - - - - - - - -Example 6: Choices from a callback (Docblock Annotations) ---------------------------------------------------------- - -Here you see how the mapping of Listing 6 is written with annotations. - -**Listing 8** - - [php] - // Application/HelloBundle/Author.php - class Author - { - /** - * @Validation({ @Choice(callback = {"Util", "getGenders"}) }) - */ - protected $gender; - } diff --git a/guides/en/Validator/Constraints/Collection.markdown b/guides/en/Validator/Constraints/Collection.markdown deleted file mode 100644 index 832f1e549a1..00000000000 --- a/guides/en/Validator/Constraints/Collection.markdown +++ /dev/null @@ -1,117 +0,0 @@ -Collection -========== - -Validates array entries against different constraints. - - [yml] - - Collection: - fields: - key1: - - NotNull: ~ - key2: - - MinLength: 10 - -Options -------- - - * `fields` (required): An associative array of array keys and one or more - constraints - * `allowMissingFields`: Whether some of the keys may not be present in the - array. Default: `false` - * `allowExtraFields`: Whether the array may contain keys not present in the - `fields` option. Default: `false` - * `missingFieldsMessage`: The error message if the `allowMissingFields` - validation fails - * `allowExtraFields`: The error message if the `allowExtraFields` validation - fails - -Example 1 (YAML): ------------------ - -Let's validate an array with two indexes `firstName` and `lastName`. The value -of `firstName` must not be blank, while the value of `lastName` must not be -blank with a minimum length of four characters. Furthermore, both keys -may not exist in the array. - -**Listing 1** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - options: - - Collection: - fields: - firstName: - - NotBlank: ~ - lastName: - - NotBlank: ~ - - MinLength: 4 - allowMissingFields: true - -The following object would fail the validation. - -**Listing 2** - - [php] - $author = new Author(); - $author->options['firstName'] = null; - $author->options['lastName'] = 'foo'; - - print $validator->validate($author); - -You should see the following error messages: - - Application\HelloBundle\Author.options[firstName]: - This value should not be null - Application\HelloBundle\Author.options[lastName]: - This value is too short. It should have 4 characters or more - -Example 2 (XML): ----------------- - -This example shows the same mapping as in Example 1 using XML. - -**Listing 3** - - [xml] - - - - - - - - - - -Example 3 (Docblock Annotations): ---------------------------------- - -This example shows the mapping from Example 1 with Docblock Annotations. - -**Listing 4** - - [php] - // Application/HelloBundle/Author.php - class Author - { - /** - * @Validation({ @Collection( - * fields = { - * "firstName" = @NotNull, - * "lastName" = { @NotBlank, @MinLength(4) } - * }, - * allowMissingFields = true - * )}) - */ - private $options = array(); - } \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Email.markdown b/guides/en/Validator/Constraints/Email.markdown deleted file mode 100644 index 59c9b06b8b5..00000000000 --- a/guides/en/Validator/Constraints/Email.markdown +++ /dev/null @@ -1,15 +0,0 @@ -Email -===== - -Validates that a value is a valid email address. - - [yml] - properties: - email: - - Email: ~ - -Options -------- - - * `checkMX`: Whether MX records should be checked for the domain. Default: `false` - * `message`: The error message if the validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/File.markdown b/guides/en/Validator/Constraints/File.markdown deleted file mode 100644 index 7acc45f20ee..00000000000 --- a/guides/en/Validator/Constraints/File.markdown +++ /dev/null @@ -1,82 +0,0 @@ -File -==== - -Validates that a value is the path to an existing file. - - [yml] - properties: - filename: - - File: ~ - -Options -------- - - * `maxSize`: The maximum allowed file size. Can be provided in bytes, kilobytes - (with the suffix "k") or megabytes (with the suffix "M") - * `mimeTypes`: One or more allowed mime types - * `notFoundMessage`: The error message if the file was not found - * `notReadableMessage`: The error message if the file could not be read - * `maxSizeMessage`: The error message if `maxSize` validation fails - * `mimeTypesMessage`: The error message if `mimeTypes` validation fails - -Example 1: Validating the file size and mime type (YAML) --------------------------------------------------------- - -In this example we use the `File` constraint to verify that the file does -not exceed a maximum size of 128 kilobytes and is a PDF document. - -**Listing 1** - - [yml] - properties: - filename: - - File: { maxSize: 128k, mimeTypes: [application/pdf, application/x-pdf] } - -When you validate the object with a file that doesn't satisfy one of these -constraints, a proper error message is returned by the validator. - - Application\HelloBundle\Author.filename: - The file is too large (150 kB). Allowed maximum size is 128 kB - -Example 2: Validating the file size and mime type (XML) -------------------------------------------------------- - -This listing shows the example of Listing 1 using XML. - -**Listing 2** - - [xml] - - - - - - - - - - -Example 3: Validating the file size and mime type (Docblock Annotations) ------------------------------------------------------------------------- - -As always it is possible to map Listing 1 with annotations, too. - -**Listing 3** - - [php] - // Application/HelloBundle/Author.php - class Author - { - /** - * @Validation({ - * @File(maxSize = "128k", mimeTypes = { - * "application/pdf", - * "application/x-pdf" - * }) - * }) - */ - private $filename; - } diff --git a/guides/en/Validator/Constraints/Max.markdown b/guides/en/Validator/Constraints/Max.markdown deleted file mode 100644 index 778abffbdc7..00000000000 --- a/guides/en/Validator/Constraints/Max.markdown +++ /dev/null @@ -1,15 +0,0 @@ -Max -=== - -Validates that a value is not greater than the given limit. - - [yml] - properties: - age: - - Max: 99 - -Options -------- - - * `limit` (**default**, required): The limit - * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/MaxLength.markdown b/guides/en/Validator/Constraints/MaxLength.markdown deleted file mode 100644 index 2c19397f125..00000000000 --- a/guides/en/Validator/Constraints/MaxLength.markdown +++ /dev/null @@ -1,15 +0,0 @@ -MaxLength -========= - -Validates that the string length of a value is not greater than the given limit. - - [yml] - properties: - firstName: - - MaxLength: 20 - -Options -------- - - * `limit` (**default**, required): The limit - * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Min.markdown b/guides/en/Validator/Constraints/Min.markdown deleted file mode 100644 index 0295fbbb859..00000000000 --- a/guides/en/Validator/Constraints/Min.markdown +++ /dev/null @@ -1,15 +0,0 @@ -Min -=== - -Validates that a value is not smaller than the given limit. - - [yml] - properties: - age: - - Min: 1 - -Options -------- - - * `limit` (**default**, required): The limit - * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/MinLength.markdown b/guides/en/Validator/Constraints/MinLength.markdown deleted file mode 100644 index 64bcd59019d..00000000000 --- a/guides/en/Validator/Constraints/MinLength.markdown +++ /dev/null @@ -1,15 +0,0 @@ -MinLength -========= - -Validates that the string length of a value is not smaller than the given limit. - - [yml] - properties: - firstName: - - MinLength: 3 - -Options -------- - - * `limit` (**default**, required): The limit - * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/NotBlank.markdown b/guides/en/Validator/Constraints/NotBlank.markdown deleted file mode 100644 index 2c73d3a6cb6..00000000000 --- a/guides/en/Validator/Constraints/NotBlank.markdown +++ /dev/null @@ -1,15 +0,0 @@ -NotBlank -======== - -Validates that a value is not empty (as determined by the -[`empty`](http://php.net/empty) construct). - - [yml] - properties: - firstName: - - NotBlank: ~ - -Options -------- - - * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/NotNull.markdown b/guides/en/Validator/Constraints/NotNull.markdown deleted file mode 100644 index 392698a71d6..00000000000 --- a/guides/en/Validator/Constraints/NotNull.markdown +++ /dev/null @@ -1,14 +0,0 @@ -NotNull -======= - -Validates that a value is not `null`. - - [yml] - properties: - firstName: - - NotNull: ~ - -Options -------- - - * `message`: The error message if validation fails diff --git a/guides/en/Validator/Constraints/Regex.markdown b/guides/en/Validator/Constraints/Regex.markdown deleted file mode 100644 index 8258a0ae53c..00000000000 --- a/guides/en/Validator/Constraints/Regex.markdown +++ /dev/null @@ -1,17 +0,0 @@ -Regex -===== - -Validates that a value matches a regular expression. - - [yml] - properties: - title: - - Regex: /\w+/ - -Options -------- - - * `pattern` (**default**, required): The regular expression pattern - * `match`: Whether the pattern must be matched or must not be matched. - Default: `true` - * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Time.markdown b/guides/en/Validator/Constraints/Time.markdown deleted file mode 100644 index b1beda39305..00000000000 --- a/guides/en/Validator/Constraints/Time.markdown +++ /dev/null @@ -1,14 +0,0 @@ -Time -==== - -Validates that a value is a valid time string with format "HH:MM:SS". - - [yml] - properties: - createdAt: - - DateTime: ~ - -Options -------- - - * `message`: The error message if the validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Url.markdown b/guides/en/Validator/Constraints/Url.markdown deleted file mode 100644 index 80f4a59f01b..00000000000 --- a/guides/en/Validator/Constraints/Url.markdown +++ /dev/null @@ -1,16 +0,0 @@ -Url -=== - -Validates that a value is a valid URL string. - - [yml] - properties: - website: - - Url: ~ - -Options -------- - - * `protocols`: A list of allowed protocols. Default: "http", "https", "ftp" - and "ftps". - * `message`: The error message if validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/Valid.markdown b/guides/en/Validator/Constraints/Valid.markdown deleted file mode 100644 index 5568b8151bc..00000000000 --- a/guides/en/Validator/Constraints/Valid.markdown +++ /dev/null @@ -1,117 +0,0 @@ -Valid -===== - -Validates an associated object. - - [yml] - properties: - address: - - Valid: ~ - -Options -------- - - * `class`: The expected class of the object - * `message`: The error message if the class doesn't match - -Example 1: Validate object trees (YAML) ---------------------------------------- - -This constraint helps to validate whole object trees. In the following example, -we create two classes `Author` and `Address` that both have constraints on -their properties. Furthermore, `Author` stores an `Address` instance in the -`$address` property. - -**Listing 1** - - [php] - // Application/HelloBundle/Address.php - class Address - { - protected $street; - protected $zipCode; - } - -**Listing 2** - - [php] - // Application/HelloBundle/Author.php - class Author - { - protected $firstName; - protected $lastName; - protected $address; - } - -**Listing 3** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Address: - properties: - street: - - NotBlank: ~ - zipCode: - - NotBlank: ~ - - MaxLength: 5 - - Application\HelloBundle\Author: - properties: - firstName: - - NotBlank: ~ - - MinLength: 4 - lastName: - - NotBlank: ~ - -With this mapping it is possible to successfully validate an author with an -invalid address. To prevent that, we add the `Valid` constraint to the -`$address` property. - -**Listing 4** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - address: - - Valid: ~ - -We can even go one step further and validate the class of the related object -to be `Address` or one of its subclasses. - -**Listing 5** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - address: - - Valid: { class: Application\ḨelloBundle\Address } - -Example 2: Validate object trees (XML) --------------------------------------- - -The following code snippet shows the mapping of Listing 5 in XML. - - [xml] - - - - Application\HelloBundle\Address - - - -Example 3: Validate object trees (Docblock Annotations) -------------------------------------------------------- - -With annotations, the mapping of Listing 5 looks like this: - - [php] - // Application/HelloBundle/Author.php - class Author - { - /** - * @Validation({ @Valid(class = "Application\HelloBundle\Address") }) - */ - protected $address; - } diff --git a/guides/en/Validator/Mapping.markdown b/guides/en/Validator/Mapping.markdown deleted file mode 100644 index 7277815bbeb..00000000000 --- a/guides/en/Validator/Mapping.markdown +++ /dev/null @@ -1,55 +0,0 @@ -Constraint Mapping -================== - -The mapping of constraints to classes, properties and getters takes place -in the mapping. Symfony2 supports YAML, XML, PHP and Docblock Annotations as -mapping drivers. - -Let's look at the YAML driver for now. We start with a simple example class -`Author`. - -**Listing 1** - - [php] - // Application/HelloBundle/Author.php - class Author - { - public $firstName; - public $lastName; - - public function getFullName() - { - return $this->firstName.' '.$this->lastName; - } - } - -Now we want to put some simple constraints on this class. - - * The first and last name should not be blank - - * The first and last name together should have at least 10 characters - -To map these constraints with YAML, create a new `validation.yml` mapping file -in your bundle. - -**Listing 2** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - firstName: - - NotBlank: ~ - lastName: - - NotBlank: ~ - getters: - fullName: - - MinLength: 10 - -As you can see, the mapping is very straight-forward. - ->**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. \ No newline at end of file diff --git a/guides/en/Validator/Overview.markdown b/guides/en/Validator/Overview.markdown deleted file mode 100644 index 285d4b5b4ec..00000000000 --- a/guides/en/Validator/Overview.markdown +++ /dev/null @@ -1,72 +0,0 @@ -The Validator -============= - -Validation is a very common task in web applications. Data entered in forms -needs to be validated. Data also needs to be validated before it is written -into a database or passed to a web service. - -Symfony2 comes with a new Validator component that makes this task very easy. -This component is based on the [JSR303 Bean Validation specification][1]. -What? A Java specification in PHP? You heard right, but it's not as bad as it -sounds. Let's look at how we use it in PHP. - -Example -------- - -The validator validates objects against [constraints](Constraints). Let's start -with the simple constraint that the `$name` property of a class `Author` must -not be empty. - -**Listing 1** - - [php] - // Application/HelloBundle/Author.php - class Author - { - private $name; - } - -**Listing 2** - - [yml] - # Application/HelloBundle/Resources/config/validation.yml - Application\HelloBundle\Author: - properties: - name: - - NotBlank: ~ - -Listing 2 shows a YAML file that connects properties of the class with -constraints. This process is called the [mapping](Mapping). - -Finally, we can use the `Validator` class for [validation](Validation). Symfony2 -provides a validator instance as a service in the Dependency Injection -Container. To use that service, adapt your application configuration. - -**Listing 3** - - [yml] - # config.yml - web.config: - validation: - enabled: true - -Now call the `validate()` method on the service, which delivers a list of -errors if validation fails. - -**Listing 4** - - [php] - $validator = $container->getService('validator'); - $author = new Author(); - - print $validator->validate($author); - -Because the `$name` property is empty, you will see the following error -message. - - Application\HelloBundle\Author.name: - This value should not be blank - -Insert a value into the property and the error message will disappear. - -[1]: http://jcp.org/en/jsr/detail?id=303 \ No newline at end of file diff --git a/guides/validation.rst b/guides/validation.rst deleted file mode 100644 index 72689fbe5c9..00000000000 --- a/guides/validation.rst +++ /dev/null @@ -1,498 +0,0 @@ -.. index:: - single: Forms; Validators - single: Validators - -Validation -========== - -The Basics ----------- - -The Symfony2 Validator component is based on the `JSR303 Bean Validation -specification`_. What? A Java specification in PHP? You heard right, but it's -not as bad as it sounds. Let's look at how we use it in PHP. - -The Validator is designed to validate objects against different constraints. -These constraints can be put on the class itself, on properties and on methods -prefixed with "get" or "is". Let's look at a sample configuration:: - - class Author - { - /** - * @validation:NotBlank - * @validation:MinLength(4) - */ - public $firstName; - - /** - * @validation:Email(message="Ok, seriously now. Your email address please") - */ - public function getEmail() - { - return 'foobar'; - } - } - -This snippet shows a very simple ``Author`` class with a property and a getter. -Each constraint has a name, most of them also have a couple of options. Here we -configured the constraints with annotations, but Symfony2 also offers many -other configuration drivers. - -Because the annotation driver depends on the Doctrine library, it is not -enabled by default. You can enable it in your ``config.yml``: - -.. code-block:: yaml - - # hello/config/config.yml - app.config: - validation: - enabled: true - annotations: true - -Now let's try to validate an object:: - - $author = new Author(); - $author->firstName = 'B.'; - - print $this['validator']->validate($author); - -You should see the following output: - -.. code-block:: yaml - - Author.firstName: - This value is too short. It should have 4 characters or more - Author.email: - Ok, seriously now. Your email address please - -The ``validate()`` method returns a ``ConstraintViolationList`` object that can -simply be printed or processed in your code. That was easy! - -.. index:: - single: Validators; Constraints - -The Constraints ---------------- - -Symfony2 bundles many different constraints. The following list will show you -which ones are available and how you can use and configure them. Some -constraints have a default option. If you only set this option, you can leave -away the option name:: - - /** @validation:Min(limit=3) */ - -is identical to:: - - /** @validation:Min(3) */ - -AssertFalse -~~~~~~~~~~~ - -Validates that a value is ``false``. Very useful for testing return values of -methods:: - - /** @validation:AssertFalse */ - public function isInjured(); - -Options: - -* ``message``: The error message if validation fails - -AssertTrue -~~~~~~~~~~ - -Works like ``AssertFalse``. - -NotBlank -~~~~~~~~ - -Validates that a value is not empty:: - - /** @validation:NotBlank */ - private $firstName; - -Options: - -* ``message``: The error message if validation fails - -Blank -~~~~~ - -Works like ``NotBlank``. - -NotNull -~~~~~~~ - -Validates that a value is not ``NULL``:: - - /** @validation:NotNull */ - private $firstName; - -Options: - -* ``message``: The error message if validation fails - -Null -~~~~ - -Works like ``NotNull``. - -AssertType -~~~~~~~~~~ - -Validates that a value has a specific data type:: - - /** @validation:AssertType("integer") */ - private $age; - -Options: - -* ``type`` (default): The type -* ``message``: The error message if validation fails - -Choice -~~~~~~ - -Validates that a value is one or more of a list of choices:: - - /** @validation:Choice({"male", "female"}) */ - private $gender; - -Options: - -* ``choices`` (default): The available choices -* ``callback``: Can be used instead of ``choices``. A static callback method - returning the choices. If you set this to a string, the method is expected - to be in the validated class. -* ``multiple``: Whether multiple choices are allowed. Default: ``false`` -* ``min``: The minimum amount of selected choices -* ``max``: The maximum amount of selected choices -* ``message``: The error message if validation fails -* ``minMessage``: The error message if ``min`` validation fails -* ``maxMessage``: The error message if ``max`` validation fails - -Valid -~~~~~ - -Validates that an object is valid. Can be put on properties or getters to -validate related objects:: - - /** @validation:Valid */ - private $address; - -Options: - -* ``class``: The expected class of the object (optional) -* ``message``: The error message if the class doesn't match - -Collection -~~~~~~~~~~ - -Validates array entries against different constraints:: - - /** - * @validation:Collection( - * fields = { - * "firstName" = @validation:NotNull, - * "lastName" = { @validation:NotBlank, @validation:MinLength(4) } - * }, - * allowMissingFields = true - * ) - */ - private $options = array(); - -Options: - -* ``fields`` (default): An associative array of array keys and one or more - constraints -* ``allowMissingFields``: Whether some of the keys may not be present in the - array. Default: ``false`` -* ``allowExtraFields``: Whether the array may contain keys not present in the - ``fields`` option. Default: ``false`` -* ``missingFieldsMessage``: The error message if the ``allowMissingFields`` - validation fails -* ``extraFieldsMessage``: The error message if the ``allowExtraFields`` - validation fails - -Date -~~~~ - -Validates that a value is a valid date string with format ``YYYY-MM-DD``:: - - /** @validation:Date */ - private $birthday; - -Options: - -* ``message``: The error message if the validation fails - -DateTime -~~~~~~~~ - -Validates that a value is a valid datetime string with format ``YYYY-MM-DD -HH:MM:SS``:: - - /** @validation:DateTime */ - private $createdAt; - -Options: - -* ``message``: The error message if the validation fails - -Time -~~~~ - -Validates that a value is a valid time string with format ``HH:MM:SS``:: - - /** @validation:Time */ - private $start; - -Options: - -* ``message``: The error message if the validation fails - -Email -~~~~~ - -Validates that a value is a valid email address:: - - /** @validation:Email */ - private $email; - -Options: - -* ``message``: The error message if the validation fails -* ``checkMX``: Whether MX records should be checked for the domain. Default: - ``false`` - -File -~~~~ - -Validates that a value is an existing file:: - - /** @validation:File(maxSize="64k") */ - private $filename; - -Options: - -* ``maxSize``: The maximum allowed file size. Can be provided in bytes, - kilobytes (with the suffix "k") or megabytes (with the suffix "M") -* ``mimeTypes``: One or more allowed mime types -* ``notFoundMessage``: The error message if the file was not found -* ``notReadableMessage``: The error message if the file could not be read -* ``maxSizeMessage``: The error message if ``maxSize`` validation fails -* ``mimeTypesMessage``: The error message if ``mimeTypes`` validation fails - -Max -~~~ - -Validates that a value is at most the given limit:: - - /** @validation:Max(99) */ - private $age; - -Options: - -* ``limit`` (default): The limit -* ``message``: The error message if validation fails - -Min -~~~ - -Works like ``Max``. - -MaxLength -~~~~~~~~~ - -Validates that the string length of a value is at most the given limit:: - - /** @validation:MaxLength(32) */ - private $hash; - -Options: - -* ``limit`` (default): The size limit -* ``message``: The error message if validation fails - -MinLength -~~~~~~~~~ - -Works like ``MaxLength``. - -Regex -~~~~~ - -Validates that a value matches the given regular expression:: - - /** @validation:Regex("/\w+/") */ - private $title; - -Options: - -* ``pattern`` (default): The regular expression pattern -* ``match``: Whether the pattern must be matched or must not be matched. - Default: ``true`` -* ``message``: The error message if validation fails - -Url -~~~ - -Validates that a value is a valid URL:: - - /** @validation:Url */ - private $website; - -Options: - -* ``protocols``: A list of allowed protocols. Default: "http", "https", "ftp" - and "ftps". -* ``message``: The error message if validation fails - -.. index:: - single: Validators; Configuration - -Custom Constraints ------------------- - -You can create a custom constraint by extending the base constraint class, -``Symfony\Component\Validator\Constraint``. Options for your constraint are -represented by public properties on the constraint class. For example, the -``Url`` constraint includes ``message`` and ``protocols`` properties:: - - namespace Symfony\Component\Validator\Constraints; - - class Url extends \Symfony\Component\Validator\Constraint - { - public $message = 'This value is not a valid URL'; - public $protocols = array('http', 'https', 'ftp', 'ftps'); - } - -As you can see, a constraint class is fairly minimal. The actual validation is -performed by a another "constraint validator" class. Which constraint -validator is specified by the constraint's ``validatedBy()`` method, which -includes some simple default logic:: - - // in the base Symfony\Component\Validator\Constraint class - public function validatedBy() - { - return get_class($this).'Validator'; - } - -Constraint Validators with Dependencies -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your constraint validator has dependencies, such as a database connection, -it will need to be configured as a service in the dependency injection -container. This service must include the `validator.constraint_validator` tag -and an `alias` attribute: - -.. configuration-block:: - - .. code-block:: yaml - - services: - validator.unique.your_validator_name: - class: Fully\Qualified\Validator\Class\Name - tags: - - { name: validator.constraint_validator, alias: alias_name } - - .. code-block:: xml - - - - - - - .. code-block:: php - - $container - ->register('validator.unique.your_validator_name', 'Fully\Qualified\Validator\Class\Name') - ->addTag('validator.constraint_validator', array('alias' => 'alias_name')) - ; - -Your constraint class may now use this alias to reference the appropriate -validator:: - - public function validatedBy() - { - return 'alias_name'; - } - -Other Configuration Drivers ---------------------------- - -As always in Symfony2, there are multiple ways of configuring the constraints -for your classes. Symfony2 supports the following four drivers. - -XML Configuration -~~~~~~~~~~~~~~~~~ - -The XML driver is a little verbose, but has the benefit that the XML file can -be validated to prevent errors. To use the driver, simply put a file called -``validation.xml`` in the ``Resources/config/`` directory of your bundle: - -.. code-block:: xml - - - - - - - - 4 - - - - - - - - - -YAML Configuration -~~~~~~~~~~~~~~~~~~ - -The YAML driver offers the same functionality as the XML driver. To use it, put -the file ``validation.yml`` in the ``Resources/config/`` directory of your -bundle: - -.. code-block:: yaml - - Application\HelloBundle\Model\Author: - properties: - firstName: - - NotBlank: ~ - - MinLength: 4 - - getters: - email: - - Email: { message: "Ok, seriously now. Your email address please" } - -PHP Configuration -~~~~~~~~~~~~~~~~~ - -If you prefer to write configurations in plain old PHP, you can add the static -method ``loadValidatorMetadata()`` to the classes that you want to validate:: - - use Symfony\Component\Validator\Constraints; - use Symfony\Component\Validator\Mapping\ClassMetadata; - - class Author - { - public static function loadValidatorMetadata(ClassMetadata $metadata) - { - $metadata->addPropertyConstraint('firstName', new Constraints\NotBlank()); - $metadata->addPropertyConstraint('firstName', new Constraints\MinLength(3)); - $metadata->addGetterConstraint('email', new Constraints\Email(array( - 'message' => 'Ok, seriously now. Your email address please', - ))); - } - } - -You can use either of the configuration drivers, or all together. Symfony2 will -merge all the information it can find. - -.. _JSR303 Bean Validation specification: http://jcp.org/en/jsr/detail?id=303 diff --git a/guides/validator/constraints.markdown b/guides/validator/constraints.markdown new file mode 100644 index 00000000000..bfc98e3e118 --- /dev/null +++ b/guides/validator/constraints.markdown @@ -0,0 +1,218 @@ +Constraints +=========== + +The Validator is designed to validate objects against *constraints*. +In real life, a constraint could be: "The cake must not be burned". In +Symfony2, constraints are similar: They are assertions that a condition is +true. + +Supported Constraints +--------------------- + +The following constraints are natively available in Symfony2: + +* `AssertFalse `_ +* `AssertTrue `_ +* `AssertType `_ +* `Choice `_ +* `Collection `_ +* `Date `_ +* `DateTime `_ +* `Email `_ +* `File `_ +* `Max `_ +* `MaxLength `_ +* `Min `_ +* `MinLength `_ +* `NotBlank `_ +* `NotNull `_ +* `Regex `_ +* `Time `_ +* `Url `_ +* `Valid `_ + +Constraint Targets +------------------ + +Constraints can be put on properties of a class, on public getters and on the +class itself. The benefit of class constraints is that they can validate +the whole state of an object at once, with all of its properties and methods. + +Properties +~~~~~~~~~~ + +Validating class properties is the most basic validation technique. Symfony2 +allows you to validate private, protected or public properties. The next listing +shows how to configure the properties ``$firstName`` and ``$lastName`` of a class +``Author`` to have at least 3 characters. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + firstName: + - NotBlank: ~ + - MinLength: 3 + lastName: + - NotBlank: ~ + - MinLength: 3 + + .. code-block:: xml + + + + + + 3 + + + + 3 + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:NotBlank() + * @validation:MinLength(3) + */ + private $firstName; + + /** + * @validation:NotBlank() + * @validation:MinLength(3) + */ + private $firstName; + } + +Getters +~~~~~~~ + +The next validation technique is to constrain the return value of a method. +Symfony2 allows you to constrain any public method whose name starts with +"get" or "is". In this guide, this is commonly referred to as "getter". + +The benefit of this technique is that it allows you to validate your object +dynamically. Depending on the state of your object, the method may return +different values which are then validated. + +The next listing shows you how to use the `AssertTrue `_ +constraint to validate whether a dynamically generated token is correct. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + getters: + tokenValid: + - AssertTrue: { message: "The token is invalid" } + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:AssertTrue(message = "The token is invalid") + */ + public function isTokenValid() + { + // return true or false + } + } + +.. 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. + +Custom Constraints +------------------ + +You can create a custom constraint by extending the base constraint class, +:class::`Symfony\Component\Validator\Constraint`::. Options for your constraint are +represented by public properties on the constraint class. For example, the +``Url`` constraint includes ``message`` and ``protocols`` properties:: + + namespace Symfony\Component\Validator\Constraints; + + class Url extends \Symfony\Component\Validator\Constraint + { + public $message = 'This value is not a valid URL'; + public $protocols = array('http', 'https', 'ftp', 'ftps'); + } + +As you can see, a constraint class is fairly minimal. The actual validation is +performed by a another "constraint validator" class. Which constraint +validator is specified by the constraint's ``validatedBy()`` method, which +includes some simple default logic:: + + // in the base Symfony\Component\Validator\Constraint class + public function validatedBy() + { + return get_class($this).'Validator'; + } + +Constraint Validators with Dependencies +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your constraint validator has dependencies, such as a database connection, +it will need to be configured as a service in the dependency injection +container. This service must include the ``validator.constraint_validator`` tag +and an ``alias`` attribute: + +.. configuration-block:: + + .. code-block:: yaml + + services: + validator.unique.your_validator_name: + class: Fully\Qualified\Validator\Class\Name + tags: + - { name: validator.constraint_validator, alias: alias_name } + + .. code-block:: xml + + + + + + + .. code-block:: php + + $container + ->register('validator.unique.your_validator_name', 'Fully\Qualified\Validator\Class\Name') + ->addTag('validator.constraint_validator', array('alias' => 'alias_name')) + ; + +Your constraint class may now use this alias to reference the appropriate +validator: + +.. code-block:: php + + public function validatedBy() + { + return 'alias_name'; + } \ No newline at end of file diff --git a/guides/validator/constraints/AssertFalse.rst b/guides/validator/constraints/AssertFalse.rst new file mode 100644 index 00000000000..e91c64de5cf --- /dev/null +++ b/guides/validator/constraints/AssertFalse.rst @@ -0,0 +1,18 @@ +AssertTrue +========== + +Validates that a value is ``false``. + +.. code-block:: yaml + + properties: + deleted: + - AssertFalse: ~ + +Options +------- + +* ``message``: The error message if validation fails + + +See `AssertTrue `_. \ No newline at end of file diff --git a/guides/validator/constraints/AssertTrue.rst b/guides/validator/constraints/AssertTrue.rst new file mode 100644 index 00000000000..3c05b7f0a25 --- /dev/null +++ b/guides/validator/constraints/AssertTrue.rst @@ -0,0 +1,83 @@ +AssertTrue +========== + +Validates that a value is ``true``. + +.. code-block:: yaml + + properties: + termsAccepted: + - AssertTrue: ~ + +Options +------- + +* ``message``: The error message if validation fails + + +Example +------- + +This constraint is very useful to execute custom validation logic. You can +put the logic in a method which returns either ``true`` or ``false``. + +.. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + protected $token; + + public function isTokenValid() + { + return $this->token == $this->generateToken(); + } + } + +Then you can constrain this method with ``AssertTrue``. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + getters: + tokenValid: + - AssertTrue: { message: "The token is invalid" } + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + namespace Application\HelloBundle; + + class Author + { + protected $token; + + /** + * @validation:AssertTrue(message = "The token is invalid") + */ + public function isTokenValid() + { + return $this->token == $this->generateToken(); + } + } + +If the validation of this method fails, you will see a message similar to this: + +:: + + Application\HelloBundle\Author.tokenValid: + This value should not be null diff --git a/guides/validator/constraints/AssertType.rst b/guides/validator/constraints/AssertType.rst new file mode 100644 index 00000000000..0996805ffbb --- /dev/null +++ b/guides/validator/constraints/AssertType.rst @@ -0,0 +1,34 @@ +AssertType +========== + +Validates that a value has a specific data type + +.. code-block:: yaml + + properties: + age: + - AssertType: integer + +Options +------- + +* ``type`` (**default**, required): A fully qualified class name or one of the + PHP datatypes as determined by PHP's ``is_`` functions. + + * `array `_ + * `bool `_ + * `callable `_ + * `float `_ + * `double `_ + * `int `_ + * `integer `_ + * `long `_ + * `null `_ + * `numeric `_ + * `object `_ + * `real `_ + * `resource `_ + * `scalar `_ + * `string `_ + +* ``message``: The error message in case the validation fails diff --git a/guides/validator/constraints/Choice.rst b/guides/validator/constraints/Choice.rst new file mode 100644 index 00000000000..c462d3375c0 --- /dev/null +++ b/guides/validator/constraints/Choice.rst @@ -0,0 +1,154 @@ +Choice +====== + +Validates that a value is one or more of a list of choices. + +.. code-block:: yaml + + properties: + gender: + - Choice: [male, female] + +Options +------- + +* ``choices`` (**default**, required): The available choices +* ``callback``: Can be used instead of ``choices``. A static callback method + returning the choices. If you pass a string, it is expected to be + the name of a static method in the validated class. +* ``multiple``: Whether multiple choices are allowed. Default: ``false`` +* ``min``: The minimum amount of selected choices +* ``max``: The maximum amount of selected choices +* ``message``: The error message if validation fails +* ``minMessage``: The error message if ``min`` validation fails +* ``maxMessage``: The error message if ``max`` validation fails + +Example 1: Choices as static array +---------------------------------- + +If the choices are few and easy to determine, they can be passed to the +constraint definition as array. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + gender: + - Choice: [male, female] + + .. code-block:: xml + + + + + + male + female + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:Choice({"male", "female"}) + */ + protected $gender; + } + +Example 2: Choices from a callback +---------------------------------- + +When you also need the choices in other contexts (such as a drop-down box in +a form), it is more flexible to bind them to your domain model using a static +callback method. + +.. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + public static function getGenders() + { + return array('male', 'female'); + } + } + +You can pass the name of this method to the ``callback`` option of the ``Choice`` +constraint. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + gender: + - Choice: { callback: getGenders } + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:Choice(callback = "getGenders") + */ + protected $gender; + } + +If the static callback is stored in a different class, for example ``Util``, +you can pass the class name and the method as array. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + gender: + - Choice: { callback: [Util, getGenders] } + + .. code-block:: xml + + + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:Choice(callback = {"Util", "getGenders"}) + */ + protected $gender; + } diff --git a/guides/validator/constraints/Collection.rst b/guides/validator/constraints/Collection.rst new file mode 100644 index 00000000000..6e0a8477e3f --- /dev/null +++ b/guides/validator/constraints/Collection.rst @@ -0,0 +1,109 @@ +Collection +========== + +Validates array entries against different constraints. + +.. code-block:: yaml + + - Collection: + fields: + key1: + - NotNull: ~ + key2: + - MinLength: 10 + +Options +------- + +* ``fields`` (required): An associative array of array keys and one or more + constraints +* ``allowMissingFields``: Whether some of the keys may not be present in the + array. Default: ``false`` +* ``allowExtraFields``: Whether the array may contain keys not present in the + ``fields`` option. Default: ``false`` +* ``missingFieldsMessage``: The error message if the ``allowMissingFields`` + validation fails +* ``allowExtraFields``: The error message if the ``allowExtraFields`` validation + fails + +Example: +-------- + +Let's validate an array with two indexes ``firstName`` and ``lastName``. The +value of ``firstName`` must not be blank, while the value of ``lastName`` must +not be blank with a minimum length of four characters. Furthermore, both keys +may not exist in the array. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + options: + - Collection: + fields: + firstName: + - NotBlank: ~ + lastName: + - NotBlank: ~ + - MinLength: 4 + allowMissingFields: true + + .. code-block:: xml + + + + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:Collection( + * fields = { + * "firstName" = @validation:NotNull, + * "lastName" = { @validation:NotBlank, @validation:MinLength(4) } + * }, + * allowMissingFields = true + * ) + */ + private $options = array(); + } + +The following object would fail the validation. + +.. code-block:: php + + $author = new Author(); + $author->options['firstName'] = null; + $author->options['lastName'] = 'foo'; + + print $validator->validate($author); + +You should see the following error messages: + +:: + + Application\HelloBundle\Author.options[firstName]: + This value should not be null + Application\HelloBundle\Author.options[lastName]: + This value is too short. It should have 4 characters or more + diff --git a/guides/en/Validator/Constraints/Date.markdown b/guides/validator/constraints/Date.rst similarity index 51% rename from guides/en/Validator/Constraints/Date.markdown rename to guides/validator/constraints/Date.rst index 0e6f4961f36..748e408dd97 100644 --- a/guides/en/Validator/Constraints/Date.markdown +++ b/guides/validator/constraints/Date.rst @@ -3,12 +3,13 @@ Date Validates that a value is a valid date string with format "YYYY-MM-DD". - [yml] +.. code-block:: yaml + properties: - birthday: - - Date: ~ + birthday: + - Date: ~ Options ------- - * `message`: The error message if the validation fails \ No newline at end of file +* ``message``: The error message if the validation fails \ No newline at end of file diff --git a/guides/en/Validator/Constraints/DateTime.markdown b/guides/validator/constraints/DateTime.rst similarity index 53% rename from guides/en/Validator/Constraints/DateTime.markdown rename to guides/validator/constraints/DateTime.rst index 2ecc3597ca6..47d814010d0 100644 --- a/guides/en/Validator/Constraints/DateTime.markdown +++ b/guides/validator/constraints/DateTime.rst @@ -3,12 +3,13 @@ DateTime Validates that a value is a valid datetime string with format "YYYY-MM-DD HH:MM:SS". - [yml] +.. code-block:: yaml + properties: - createdAt: - - DateTime: ~ + createdAt: + - DateTime: ~ Options ------- - * `message`: The error message if the validation fails \ No newline at end of file +* ``message``: The error message if the validation fails \ No newline at end of file diff --git a/guides/validator/constraints/Email.rst b/guides/validator/constraints/Email.rst new file mode 100644 index 00000000000..6283099f246 --- /dev/null +++ b/guides/validator/constraints/Email.rst @@ -0,0 +1,16 @@ +Email +===== + +Validates that a value is a valid email address. + +.. code-block:: yaml + + properties: + email: + - Email: ~ + +Options +------- + +* ``checkMX``: Whether MX records should be checked for the domain. Default: ``false`` +* ``message``: The error message if the validation fails \ No newline at end of file diff --git a/guides/validator/constraints/File.rst b/guides/validator/constraints/File.rst new file mode 100644 index 00000000000..273a72f5044 --- /dev/null +++ b/guides/validator/constraints/File.rst @@ -0,0 +1,73 @@ +File +==== + +Validates that a value is the path to an existing file. + +.. code-block:: yaml + + properties: + filename: + - File: ~ + +Options +------- + +* ``maxSize``: The maximum allowed file size. Can be provided in bytes, kilobytes + (with the suffix "k") or megabytes (with the suffix "M") +* ``mimeTypes``: One or more allowed mime types +* ``notFoundMessage``: The error message if the file was not found +* ``notReadableMessage``: The error message if the file could not be read +* ``maxSizeMessage``: The error message if ``maxSize`` validation fails +* ``mimeTypesMessage``: The error message if ``mimeTypes`` validation fails + +Example: Validating the file size and mime type +----------------------------------------------- + +In this example we use the ``File`` constraint to verify that the file does +not exceed a maximum size of 128 kilobytes and is a PDF document. + +.. configuration-block:: + + .. code-block:: yaml + + properties: + filename: + - File: { maxSize: 128k, mimeTypes: [application/pdf, application/x-pdf] } + + .. code-block:: xml + + + + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:File(maxSize = "128k", mimeTypes = { + * "application/pdf", + * "application/x-pdf" + * }) + */ + private $filename; + } + +When you validate the object with a file that doesn't satisfy one of these +constraints, a proper error message is returned by the validator. + +:: + + Application\HelloBundle\Author.filename: + The file is too large (150 kB). Allowed maximum size is 128 kB + diff --git a/guides/validator/constraints/Max.rst b/guides/validator/constraints/Max.rst new file mode 100644 index 00000000000..e284ef14121 --- /dev/null +++ b/guides/validator/constraints/Max.rst @@ -0,0 +1,16 @@ +Max +=== + +Validates that a value is not greater than the given limit. + +.. code-block:: yaml + + properties: + age: + - Max: 99 + +Options +------- + +* ``limit`` (**default**, required): The limit +* ``message``: The error message if validation fails \ No newline at end of file diff --git a/guides/validator/constraints/MaxLength.rst b/guides/validator/constraints/MaxLength.rst new file mode 100644 index 00000000000..3b79dc734b4 --- /dev/null +++ b/guides/validator/constraints/MaxLength.rst @@ -0,0 +1,16 @@ +MaxLength +========= + +Validates that the string length of a value is not greater than the given limit. + +.. code-block:: yaml + + properties: + firstName: + - MaxLength: 20 + +Options +------- + +* ``limit`` (**default**, required): The limit +* ``message``: The error message if validation fails \ No newline at end of file diff --git a/guides/validator/constraints/Min.rst b/guides/validator/constraints/Min.rst new file mode 100644 index 00000000000..b2c904eca15 --- /dev/null +++ b/guides/validator/constraints/Min.rst @@ -0,0 +1,16 @@ +Min +=== + +Validates that a value is not smaller than the given limit. + +.. code-block:: yaml + + properties: + age: + - Min: 1 + +Options +------- + +* ``limit`` (**default**, required): The limit +* ``message``: The error message if validation fails \ No newline at end of file diff --git a/guides/validator/constraints/MinLength.rst b/guides/validator/constraints/MinLength.rst new file mode 100644 index 00000000000..e5015e839f6 --- /dev/null +++ b/guides/validator/constraints/MinLength.rst @@ -0,0 +1,16 @@ +MinLength +========= + +Validates that the string length of a value is not smaller than the given limit. + +.. code-block:: yaml + + properties: + firstName: + - MinLength: 3 + +Options +------- + +* ``limit`` (**default**, required): The limit +* ``message``: The error message if validation fails \ No newline at end of file diff --git a/guides/validator/constraints/NotBlank.rst b/guides/validator/constraints/NotBlank.rst new file mode 100644 index 00000000000..0b0b826e4e5 --- /dev/null +++ b/guides/validator/constraints/NotBlank.rst @@ -0,0 +1,16 @@ +NotBlank +======== + +Validates that a value is not empty (as determined by the +`empty `_ construct). + +.. code-block:: yaml + + properties: + firstName: + - NotBlank: ~ + +Options +------- + +* ``message``: The error message if validation fails \ No newline at end of file diff --git a/guides/validator/constraints/NotNull.rst b/guides/validator/constraints/NotNull.rst new file mode 100644 index 00000000000..b5f4e3e04dd --- /dev/null +++ b/guides/validator/constraints/NotNull.rst @@ -0,0 +1,15 @@ +NotNull +======= + +Validates that a value is not ``null``. + +.. code-block:: yaml + + properties: + firstName: + - NotNull: ~ + +Options +------- + + * ``message``: The error message if validation fails diff --git a/guides/validator/constraints/Regex.rst b/guides/validator/constraints/Regex.rst new file mode 100644 index 00000000000..1981b5f7955 --- /dev/null +++ b/guides/validator/constraints/Regex.rst @@ -0,0 +1,18 @@ +Regex +===== + +Validates that a value matches a regular expression. + +.. code-block:: yaml + + properties: + title: + - Regex: /\w+/ + +Options +------- + +* ``pattern`` (**default**, required): The regular expression pattern +* ``match``: Whether the pattern must be matched or must not be matched. + Default: ``true`` +* ``message``: The error message if validation fails \ No newline at end of file diff --git a/guides/validator/constraints/Time.rst b/guides/validator/constraints/Time.rst new file mode 100644 index 00000000000..d9babc193be --- /dev/null +++ b/guides/validator/constraints/Time.rst @@ -0,0 +1,15 @@ +Time +==== + +Validates that a value is a valid time string with format "HH:MM:SS". + +.. code-block:: yaml + + properties: + createdAt: + - DateTime: ~ + +Options +------- + +* ``message``: The error message if the validation fails \ No newline at end of file diff --git a/guides/validator/constraints/Url.rst b/guides/validator/constraints/Url.rst new file mode 100644 index 00000000000..a669024f792 --- /dev/null +++ b/guides/validator/constraints/Url.rst @@ -0,0 +1,17 @@ +Url +=== + +Validates that a value is a valid URL string. + +.. code-block:: yaml + + properties: + website: + - Url: ~ + +Options +------- + +* ``protocols``: A list of allowed protocols. Default: "http", "https", "ftp" + and "ftps". +* ``message``: The error message if validation fails \ No newline at end of file diff --git a/guides/validator/constraints/Valid.rst b/guides/validator/constraints/Valid.rst new file mode 100644 index 00000000000..d63d509a6a7 --- /dev/null +++ b/guides/validator/constraints/Valid.rst @@ -0,0 +1,186 @@ +Valid +===== + +Validates an associated object. + +.. code-block:: yaml + + properties: + address: + - Valid: ~ + +Options +------- + + * ``class``: The expected class of the object + * ``message``: The error message if the class doesn't match + +Example: Validate object graphs +------------------------------- + +This constraint helps to validate whole object graphs. In the following example, +we create two classes ``Author`` and ``Address`` that both have constraints on +their properties. Furthermore, ``Author`` stores an ``Address`` instance in the +``$address`` property. + +.. code-block:: php + + // Application/HelloBundle/Address.php + class Address + { + protected $street; + protected $zipCode; + } + +.. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + protected $firstName; + protected $lastName; + protected $address; + } + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Address: + properties: + street: + - NotBlank: ~ + zipCode: + - NotBlank: ~ + - MaxLength: 5 + + Application\HelloBundle\Author: + properties: + firstName: + - NotBlank: ~ + - MinLength: 4 + lastName: + - NotBlank: ~ + + .. code-block:: xml + + + + + + + + + 5 + + + + + + + 4 + + + + + + + .. code-block:: php + + // Application/HelloBundle/Address.php + class Author + { + /** + * @validation:NotBlank() + */ + protected $street; + + /** + * @validation:NotBlank() + * @validation:MaxLength(5) + */ + protected $zipCode; + } + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:NotBlank() + * @validation:MinLength(4) + */ + protected $firstName; + + /** + * @validation:NotBlank() + */ + protected $lastName; + } + +With this mapping it is possible to successfully validate an author with an +invalid address. To prevent that, we add the ``Valid`` constraint to the +``$address`` property. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + address: + - Valid: ~ + + .. code-block:: xml + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:Valid() + */ + protected $address; + } + +We can even go one step further and validate the class of the related object +to be ``Address`` or one of its subclasses. + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + address: + - Valid: { class: Application\ḨelloBundle\Address } + + .. code-block:: xml + + + + + Application\HelloBundle\Address + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:Valid(class = "Application\HelloBundle\Address") + */ + protected $address; + } diff --git a/guides/validator/index.rst b/guides/validator/index.rst new file mode 100644 index 00000000000..ae6fec3107c --- /dev/null +++ b/guides/validator/index.rst @@ -0,0 +1,9 @@ +Symfony2 Validator +================== + +.. toctree:: + :maxdepth: 2 + + overview + view + twig diff --git a/guides/validator/overview.markdown b/guides/validator/overview.markdown new file mode 100644 index 00000000000..46bf83c7755 --- /dev/null +++ b/guides/validator/overview.markdown @@ -0,0 +1,89 @@ +The Validator +============= + +Validation is a very common task in web applications. Data entered in forms +needs to be validated. Data also needs to be validated before it is written +into a database or passed to a web service. + +Symfony2 ships with a new Validator component that makes this task very easy. +This component is based on the +`JSR303 Bean Validation specification `_. +What? A Java specification in PHP? You heard right, but it's not as bad as it +sounds. Let's look at how we use it in PHP. + +The validator validates objects against `constraints `_. Let's start +with the simple constraint that the ``$name`` property of a class ``Author`` must +not be empty. + +.. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + private $name; + } + +The next listing shows a YAML file that connects properties of the class with +constraints. This process is called the "mapping". + +.. configuration-block:: + + .. code-block:: yaml + + # Application/HelloBundle/Resources/config/validation.yml + Application\HelloBundle\Author: + properties: + name: + - NotBlank: ~ + + .. code-block:: xml + + + + + + + + + .. code-block:: php + + // Application/HelloBundle/Author.php + class Author + { + /** + * @validation:NotBlank() + */ + private $name; + } + +Finally, we can use the :class:`Symfony\Component\Validator\Validator`:: class +for `validation `_. Symfony2 provides a validator instance as a +service in the Dependency Injection Container. To use that service, adapt your +application configuration. + +.. code-block:: yaml + + # hello/config/config.yml + app.config: + validation: + enabled: true + +Now call the ``validate()`` method on the service, which delivers a list of +errors if validation fails. + +.. code-block:: php + + $validator = $container->getService('validator'); + $author = new Author(); + + print $validator->validate($author); + +Because the ``$name`` property is empty, you will see the following error +message. + +:: + + Application\HelloBundle\Author.name: + This value should not be blank + +Insert a value into the property and the error message will disappear. diff --git a/guides/en/Validator/Validation.markdown b/guides/validator/validation.markdown similarity index 64% rename from guides/en/Validator/Validation.markdown rename to guides/validator/validation.markdown index 831a6a13636..e18e7fcee52 100644 --- a/guides/en/Validator/Validation.markdown +++ b/guides/validator/validation.markdown @@ -1,38 +1,40 @@ Constraint Validation ===================== -Objects with constraints are validated by the `Validator` class. If you use +Objects with constraints are validated by the +:class:`Symfony\Component\Validator\Validator`:: class. If you use Symfony2, this class is already registered as a service in the Dependency Injection Container. To enable the service, add the following lines to your configuration: -**Listing 1** +.. code-block:: yaml - [yml] - # config.yml - web.config: - validation: - enabled: true + # hello/config/config.yml + app.config: + validation: + enabled: true Then you can get the validator from the container and start validating your objects. -**Listing 2** +.. code-block:: php - [php] $validator = $container->getService('validator'); $author = new Author(); print $validator->validate($author); -The `validate()` method returns a `ConstraintViolationList` object. This object -behaves exactly like an array. You can iterate over it, and you can even print +The ``validate()`` method returns a +:class:`Symfony\Component\Validator\ConstraintViolationList`:: object. This object +behaves exactly like an array. You can iterate over it and you can even print it in a nicely formatted manner. Every element of the list corresponds to one validation error. If the list is empty, it's time to dance, because then validation succeeded. The above call will output something similar to this: +:: + Application\HelloBundle\Author.firstName: This value should not be blank Application\HelloBundle\Author.lastName: @@ -40,13 +42,4 @@ The above call will output something similar to this: Application\HelloBundle\Author.fullName: This value is too short. It should have 10 characters or more -If you fill the object with correct values, you will see that the validation -errors disappear. - -### Validating Properties - -TODO - -### Validating Values - -TODO \ No newline at end of file +If you fill the object with correct values the validation errors disappear.