2
我需要更改窗體中某些字段的驗證。驗證器通過非常大的yml文件進行配置。我想知道是否有辦法一次對兩個字段進行驗證。 在我的情況下,我有兩個字段不能同時爲空。至少有一個必須填寫。依賴於另一個字段的條件字段驗證
不幸的是,直到現在我才能看到驗證是基於每個字段定義的,而不是在多個字段上。
問題是:是否有可能在標準的yml配置中執行上述驗證?
謝謝!
我需要更改窗體中某些字段的驗證。驗證器通過非常大的yml文件進行配置。我想知道是否有辦法一次對兩個字段進行驗證。 在我的情況下,我有兩個字段不能同時爲空。至少有一個必須填寫。依賴於另一個字段的條件字段驗證
不幸的是,直到現在我才能看到驗證是基於每個字段定義的,而不是在多個字段上。
問題是:是否有可能在標準的yml配置中執行上述驗證?
謝謝!
我建議你看看Custom validator,尤其是Class Constraint Validator。
我不會複製粘貼整個代碼,只是你將不得不改變的部分。
擴展Constraint
類。
的src/Acme的/ DemoBundle /識別/約束/ CheckTwoFields.php
<?php
namespace Acme\DemoBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class CheckTwoFields extends Constraint
{
public $message = 'You must fill the foo or bar field.';
public function validatedBy()
{
return 'CheckTwoFieldsValidator';
}
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}
通過擴展ConstraintValidator
類中定義的驗證,foo
和bar
是2場要檢查:
src/Acme/DemoBundle/Validator/Constraints/CheckTwoFieldsValidator.php
namespace Acme\DemoBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class CheckTwoFieldsValidator extends ConstraintValidator
{
public function validate($protocol, Constraint $constraint)
{
if ((empty($protocol->getFoo())) && (empty($protocol->getBar()))) {
$this->context->addViolationAt('foo', $constraint->message, array(), null);
}
}
}
使用驗證:
的src/Acme的/ DemoBundle /資源/配置/ validation.yml
Acme\DemoBundle\Entity\AcmeEntity:
constraints:
- Acme\DemoBundle\Validator\Constraints\CheckTwoFields: ~
感謝您接受的答案。我沒有測試過我的代碼,我很高興它爲你工作! –
是類似於這種可能使用sfValidator類的解決方案嗎? – fstab
我只知道Symfony2,而不是Symfony1,對不起。 –