Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony validate a property if another property is not not blank

I have a class

Class SubjectSegment{ 
 /**
 *@CustomAssert\MyCitizenshipNumber()
 */ 
 private $citizenshipNumber; 
 /**
 *@CustomAssert\MyDate()
 */ 
 private $citizenshipNumberIssuedDate;
}

what i really want to do is valid citizenshipNumberIssuedDate if citizenshipNumber is present...

What is the best way to achieve this

like image 506
Madhab452 Avatar asked Feb 12 '23 00:02

Madhab452


1 Answers

Hi you should look on http://symfony.com/doc/current/reference/constraints/Callback.html

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;

/**
 * @Assert\Callback(methods={"isCitizenDateValid"})
 */

Class SubjectSegment{ 
    /**
    *@CustomAssert\MyCitizenshipNumber()
    */ 
    private $citizenshipNumber; 
    /**
    *@CustomAssert\MyDate()
    */ 
    private $citizenshipNumberIssuedDate;

    public function isCitizenDateValid(ExecutionContext $context)
    {
        //Do your validation here for your exemple :
        if(null === $this->citizenshipNumber && null === $this->citizenshipNumberIssuedDate) {
            $context->addViolationAtSubPath('citizenshipNumberIssuedDate', 'The date is required', array(), null);
        }
    }
}
like image 63
pietro Avatar answered Feb 13 '23 22:02

pietro