发布于 2015-08-27 16:42:49 | 121 次阅读 | 评论: 0 | 来源: 网络整理
This constraint is used when the underlying data is a collection (i.e. an
array or an object that implements Traversable
and ArrayAccess
),
but you’d like to validate different keys of that collection in different
ways. For example, you might validate the email
key using the Email
constraint and the inventory
key of the collection with the Range
constraint.
This constraint can also make sure that certain collection keys are present and that extra keys are not present.
Applies to | property or method |
Options | |
Class | Collection |
Validator | CollectionValidator |
The Collection
constraint allows you to validate the different keys of
a collection individually. Take the following example:
// src/Acme/BlogBundle/Entity/Author.php
namespace AcmeBlogBundleEntity;
class Author
{
protected $profileData = array(
'personal_email',
'short_bio',
);
public function setProfileData($key, $value)
{
$this->profileData[$key] = $value;
}
}
To validate that the personal_email
element of the profileData
array
property is a valid email address and that the short_bio
element is not
blank but is no longer than 100 characters in length, you would do the following:
# src/Acme/BlogBundle/Resources/config/validation.yml
AcmeBlogBundleEntityAuthor:
properties:
profileData:
- Collection:
fields:
personal_email: Email
short_bio:
- NotBlank
- Length:
max: 100
maxMessage: Your short bio is too long!
allowMissingFields: true
// src/Acme/BlogBundle/Entity/Author.php
namespace AcmeBlogBundleEntity;
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
/**
* @AssertCollection(
* fields = {
* "personal_email" = @AssertEmail,
* "short_bio" = {
* @AssertNotBlank(),
* @AssertLength(
* max = 100,
* maxMessage = "Your short bio is too long!"
* )
* }
* },
* allowMissingFields = true
* )
*/
protected $profileData = array(
'personal_email',
'short_bio',
);
}
<!-- src/Acme/BlogBundle/Resources/config/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="AcmeBlogBundleEntityAuthor">
<property name="profileData">
<constraint name="Collection">
<option name="fields">
<value key="personal_email">
<constraint name="Email" />
</value>
<value key="short_bio">
<constraint name="NotBlank" />
<constraint name="Length">
<option name="max">100</option>
<option name="maxMessage">Your short bio is too long!</option>
</constraint>
</value>
</option>
<option name="allowMissingFields">true</option>
</constraint>
</property>
</class>
</constraint-mapping>
// src/Acme/BlogBundle/Entity/Author.php
namespace AcmeBlogBundleEntity;
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
private $options = array();
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('profileData', new AssertCollection(array(
'fields' => array(
'personal_email' => new AssertEmail(),
'short_bio' => array(
new AssertNotBlank(),
new AssertLength(array(
'max' => 100,
'maxMessage' => 'Your short bio is too long!',
)),
),
),
'allowMissingFields' => true,
)));
}
}
By default, this constraint validates more than simply whether or not the individual fields in the collection pass their assigned constraints. In fact, if any keys of a collection are missing or if there are any unrecognized keys in the collection, validation errors will be thrown.
If you would like to allow for keys to be absent from the collection or if
you would like “extra” keys to be allowed in the collection, you can modify
the allowMissingFields and allowExtraFields options respectively. In
the above example, the allowMissingFields
option was set to true, meaning
that if either of the personal_email
or short_bio
elements were missing
from the $personalData
property, no validation error would occur.
2.3 新版功能: The Required
and Optional
constraints were moved to the namespace
SymfonyComponentValidatorConstraints
in Symfony 2.3.
Constraints for fields within a collection can be wrapped in the Required
or
Optional
constraint to control whether they should always be applied (Required
)
or only applied when the field is present (Optional
).
For instance, if you want to require that the personal_email
field of the
profileData
array is not blank and is a valid email but the alternate_email
field is optional but must be a valid email if supplied, you can do the following:
# src/Acme/BlogBundle/Resources/config/validation.yml
AcmeBlogBundleEntityAuthor:
properties:
profile_data:
- Collection:
fields:
personal_email:
- Required
- NotBlank: ~
- Email: ~
alternate_email:
- Optional:
- Email: ~
// src/Acme/BlogBundle/Entity/Author.php
namespace AcmeBlogBundleEntity;
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
/**
* @AssertCollection(
* fields={
* "personal_email" = @AssertRequired({@AssertNotBlank, @AssertEmail}),
* "alternate_email" = @AssertOptional(@AssertEmail)
* }
* )
*/
protected $profileData = array('personal_email');
}
<!-- src/Acme/BlogBundle/Resources/config/validation.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="AcmeBlogBundleEntityAuthor">
<property name="profile_data">
<constraint name="Collection">
<option name="fields">
<value key="personal_email">
<constraint name="Required">
<constraint name="NotBlank" />
<constraint name="Email" />
</constraint>
</value>
<value key="alternate_email">
<constraint name="Optional">
<constraint name="Email" />
</constraint>
</value>
</option>
</constraint>
</property>
</class>
</constraint-mapping>
// src/Acme/BlogBundle/Entity/Author.php
namespace AcmeBlogBundleEntity;
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
protected $profileData = array('personal_email');
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('profileData', new AssertCollection(array(
'fields' => array(
'personal_email' => new AssertRequired(array(new AssertNotBlank(), new AssertEmail())),
'alternate_email' => new AssertOptional(new AssertEmail()),
),
)));
}
}
Even without allowMissingFields
set to true, you can now omit the alternate_email
property completely from the profileData
array, since it is Optional
.
However, if the personal_email
field does not exist in the array,
the NotBlank
constraint will still be applied (since it is wrapped in
Required
) and you will receive a constraint violation.
type: array
[default option]
This option is required, and is an associative array defining all of the keys in the collection and, for each key, exactly which validator(s) should be executed against that element of the collection.
type: Boolean
default: false
If this option is set to false
and the underlying collection contains
one or more elements that are not included in the fields option, a validation
error will be returned. If set to true
, extra fields are ok.
type: Boolean
default: The fields {{ fields }} were not expected.
The message shown if allowExtraFields is false and an extra field is detected.
type: Boolean
default: false
If this option is set to false
and one or more fields from the fields
option are not present in the underlying collection, a validation error will
be returned. If set to true
, it’s ok if some fields in the fields
option are not present in the underlying collection.
type: Boolean
default: The fields {{ fields }} are missing.
The message shown if allowMissingFields is false and one or more fields are missing from the underlying collection.
type: mixed
default: null
2.6 新版功能: The payload
option was introduced in Symfony 2.6.
This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to.
For example, you may want to used several error levels to present failed constraint differently in the front-end depending on the severity of the error.