'Phalcon validate field if exist post data

I've notice that phalcon validation model will do validation no matter the field do exist in post.

public function validation()
{
    $this->validate(new Uniqueness(
        array(
            "field"   => "email",
            "message" => "The email is already registered"
        )
    ));
    $this->validate(new Email(
        array(
            "field"   => "companyEmail",
            "message" => "Email format error"
        )
    ));
    return $this->validationHasFailed() != true;
}

In this case even if the user is saving other data rather than email, the email field still being verified. How to make it validate only if the field exist? ( for some field its really not needed to validate everytime )

maybe something like

if( *syntax* ){
    $this->validate(new Email(
        array(
            "field"   => "companyEmail",
            "message" => "Email format error"
        )
    ));
}


Solution 1:[1]

Use a form class (subclass of Phalcon\Forms\Form), add code to check for the existence of the variable in your beforeValidate function and only add the validator if the variable is set.

function beforeValidation($data, $entity) 
{
  ...
  $elements = $this->getElements();

  if (isset($data['fieldname'])) {
     $elements['fieldname']->addValidator(new Email(
        array(
            "field"   => "companyEmail",
            "message" => "Email format error"
        )
    ))
     ...
  }
}

Solution 2:[2]

This is my implementation for Phalcon 3.4

class SometimesOf extends \Phalcon\Validation\Validator\PresenceOf
{

    public function __construct(array $options = null)
    {
        parent::__construct($options);
        $this->setOption('allowEmpty', true);
        
        if(!$this->hasOption('message')){
            $this->setOption('message', 'Field :field cannot be empty');
        }
    }

    public function isAllowEmpty(Validation $validator, $field)
    {
        $keys = array_keys($validator->getData());
        return !in_array($field, $keys, true);
    }

}

And in the validator use it as a...

$validation->add('foo', new PresenceOf());

$validation->add('bar', new SometimesOf());

$messages = $validation->validate($data);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel
Solution 2