我需要創建Symfony 2 custom class constraint validator,以驗證屬性不等於另一個屬性(即密碼不能與用戶名匹配)。自定義Symfony 2類約束驗證程序NotEqualTo
我的第一個問題是:我需要實施方法getDefaultOption()
什麼是用於?
/**
* @Annotation
*/
class NotEqualTo extends Constraint
{
/**
* @var string
*/
public $message = "{{ property1 }} should not be equal to {{ property2 }}.";
/**
* @var string
*/
public $property1;
/**
* @var string
*/
public $property2;
/**
* {@inheritDoc}
*/
public function getRequiredOptions() { return ['property1', 'property2']; }
/**
* {@inheritDoc}
*/
public function getTargets() { return self::CLASS_CONSTRAINT; }
}
第二個問題是,如何獲取實際的對象(檢查 「property1」 和 「property2」)在我的validate()
方法?
public function validate($value, Constraint $constraint)
{
if(null === $value || '' === $value) {
return;
}
if (!is_string($constraint->property1)) {
throw new UnexpectedTypeException($constraint->property1, 'string');
}
if (!is_string($constraint->property2)) {
throw new UnexpectedTypeException($constraint->property2, 'string');
}
// Get the actual value of property1 and property2 in the object
// Check for equality
if($object->property1 === $object->property2) {
$this->context->addViolation($constraint->message, [
'{{ property1 }}' => $constraint->property1,
'{{ property2 }}' => $constraint->property2,
]);
}
}
關於第一個問題,我的選項是「property1」和「property2」,所以沒有「領先」選項。我對嗎? – gremo
@格雷莫:是的,你說得對。 – Crozin
謝謝,非常有幫助的解釋。 – gremo