0
votes

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"
        )
    ));
}
2

2 Answers

2
votes

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"
        )
    ))
     ...
  }
}
0
votes

Here my solution:

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

I'm doing this as I am passing the variable via ajax