Symfony2 form validation based on two fields

前端 未结 5 2060
醉梦人生
醉梦人生 2020-12-05 05:04

I am currently developing a Website in which user may buy gift cards. I am using a three step form using the CraueFormFlow bundle and everything is concerning the steps. I a

5条回答
  •  爱一瞬间的悲伤
    2020-12-05 05:36

    This is how I've done this in my validation constraints, to check credit card validity with expiration month and year properties.

    In this class, I check the value of expirationYear property and compare it with value of expirationMonth property got from contextObject.

    /**
     * Method to validate
     * 
     * @param string                                  $value      Property value    
     * @param \Symfony\Component\Validator\Constraint $constraint All properties
     * 
     * @return boolean
     */
    public function validate($value, Constraint $constraint)
    {
        $date               = getdate();
        $year               = (string) $date['year'];
        $month              = (string) $date['mon'];
    
        $yearLastDigits     = substr($year, 2);
        $monthLastDigits    = $month;
        $otherFieldValue    = $this->context->getRoot()->get('expirationMonth')->getData();
    
        if (!empty($otherFieldValue) && ($value <= $yearLastDigits) && 
                ($otherFieldValue <= $monthLastDigits)) {
            $this->context->addViolation(
                $constraint->message,
                array('%string%' => $value)
            );            
            return false;            
        }
    
        return true;
    }
    

    Of course, you have to authorize class and properties constraints in your getTargets method, form the main constraint file.

    /**
     * Get class constraints and properties
     * 
     * @return array
     */
    public function getTargets()
    {
        return array(self::CLASS_CONSTRAINT, self::PROPERTY_CONSTRAINT);
    } 
    

    Further explanations and complete tutorial here: http://creativcoders.wordpress.com/2014/07/19/symfony2-two-fields-comparison-with-custom-validation-constraints/

提交回复
热议问题