简体   繁体   中英

Phalcon optional fields in model validation

i have validated some fields in Phalcon model like below

class Ads extends Phalcon\Mvc\Collection
{

    public function validation()
    {
        $this->validate(
            new InclusionIn(
                array(
                    "field"   => "type",
                    "message" => "Type must be: mechanical or virtual",
                    "domain"  => array("Mechanical", "Virtual")
                )
            )
        );

        $this->validate(
            new Numericality(
                array(
                    "field"   => "price",
                    "message" => "Price must be numeric"
                )
            )
        );

        return $this->validationHasFailed() != true;
    }

}

How can i define some fields as optional fields and some fields as required fields in validation?

optional fields:
for example when price exist, validate it, when not price, ignore it.

required fields :
when price not exist, don't insert data into database and return related error message.

use allowEmpty as

$this->validate(
            new Numericality(
                array(
                    "field"   => "price",
                    "message" => "Price must be numeric",
                    "allowEmpty" => true
                )
            )
        );

When the price field is empty, it will not validate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM