YII2 - 如何为动态表单fild进行条件验证?

时间:2018-04-06 09:42:33

标签: php yii2

如何将条件验证放入动态表单中这是模型文件,address1是动态文件

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['client_id'], 'integer'],
        [['client_type', 'address1', 'address_type', 'address2', 'forn_address1', 'forn_address2', 'is_deleted', 'state', 'city', 'forn_city', 'forn_country', 'zip', 'forn_zip'], 'string'],
        [['added_on', 'updated_on'], 'safe'],
        [['zip','forn_zip'], 'match' ,'pattern'=> '/^[0-9]*$/' ,'message'=> 'Zip code must be numeric.'],
        [['address1', 'state', 'city', 'zip'], 'required', 
        'when' => function ($model) { 
            return $model->address_type == "domestic_address"; 
        }, 
        'whenClient' => "function (attribute, value) { console.log($('div.address_type label input[type=radio]:checked').val());
        return $('div.address_type label input[type=radio]:checked').val() == 'domestic_address';}"],
        [['forn_address1', 'forn_city', 'forn_zip', 'forn_country'], 'required', 'when' => function ($model) { return $model->address_type == "foreign_address"; }, 'whenClient' => "function (attribute, value) { console.log($('div.address_type label input[type=radio]:checked').val());
        return $('div.address_type label input[type=radio]:checked').val() == 'foreign_address';}"]
    ];
}

如何将条件验证放入动态表单中?

1 个答案:

答案 0 :(得分:0)

使用Standalone Validator

/**
 * @inheritdoc
 */ 
public function rules()
{
    return [
        ['address', 'validateAddress']
    ]
}

/**
* Check your address.
*/
public function validateAddress($attribute, $params, $validator)
{

   // 
   // You can access other model fields like so:
   // $this->address_type or $this->address or $this->other_field

   /* Add your conditions as you see fit.*/
   if (strtolower($this->address_type) = 'domestic_address')) {
       $this->addError($attribute, 'Address TYPE is too domestic');
   }
   // or for example 
   if (strtolower($this->address) = '123 Road-ABC')) {
       $this->addError($attribute, 'Address is goofy');
   }

}