사용자 지정 유효성 검사를 정의해야합니다. 당신은 메시지와 함께 사용자가 정의한 두 가지 방법
한 제한 조건 클래스 다음
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';
}
}
를 만들 필요가 사용자 지정 유효성 검사 제약 모두의
먼저 만들기에 제약을 진행할 수 있으며있어 발리 인 심포니에 말하는 재치를 주석으로
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. 유효성 검사기는 어디에 저장합니까? (두 번째 파일) 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