カスタム検証を定義する必要があります。あなたは、あなたがメッセージで制約を定義しているとあなたがしている。ここ制約クラスを作成する
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ConstraintZeroOrAtLeastThreeConstraint extends Constraint
{
public $message = 'Put here a validation error message';
public function validatedBy()
{
return get_class($this).'Validator';
}
}
を必要とするすべての
まずカスタム検証制約を作成
に二つの方法で
1を続行することができますバリデータがあるのsymfonyに伝えるウィットそれに注釈を付けることにより、
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ZeroOrAtLeastThreeConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!count($value)) {
return;
}
if (count($value) >= 3) {
return;
}
$this
->context
->buildValidation('You should choose zero or at least three elements')
->addViolation();
}
}
は今、あなたは財産時に、あなたのバリデータを使用することができます(私たちは、以下に定義するつもりだということ)もちろん時間@ ConstraintZeroOrAtLeastThreeConstraint
(もちろん、それはあなたが使用するために実体ファイルにインポートする必要があります)
あなたも
public function __construct($options)
{
if (!isset($options['atLeastTimes'])) {
throw new MissingOptionException(...);
}
$this->atLeastTimes = $options['atLeastTimes'];
}
2作成を使用してZeroOrAtLeastTimesConstraint
に、この制約を一般化する値0と3をカスタマイズすることができますエンティティ内のコールバック検証関数
/**
* @Assert\Callback
*/
public function validate(ExecutionContextInterface $context, $payload)
{
if (!count($this->getArticles()) {
return;
}
if (count($this->getArticles() >= 3) {
return;
}
$context
->buildViolation('You should choose 0 or at least 3 articles')
->addViolation();
}
私は最初の方法を使用しようとしていますが、私は質問があります。1.どこで制約クラスを保存しますか? 2.バリデータはどこに保存しますか? (2番目のファイル)3.このバリデーターを私の財産でどのように使用しますか? 3.それでは、ymlファイルに何を入れるべきですか? – user7808407
@ user7808407回答1と2:好きなところでは、通常は 'Validator \ Constraint'の下に制約があり、' Validator'には 'Validator'があります。答え3:あなたの 'yml'ファイルには他の制約のように使用することができます – DonCallisto
清潔にしてくれてありがとうございます。だから私はすべての手順を実行し、このエラーメッセージが表示されました。コンストレイントバリデータ "Symfony \ Component \ Validator \ Constraints \ ConstraintSeeAlsoConstraintValidator"が存在しないか、有効になっていません。あなたの制約クラス "Symfony \ Component \ Validator \ Constraints \ ConstraintSeeAlsoConstraint"の "validatedBy"メソッドをチェックしてください。 – user7808407