自定义Yii2验证器未触发

时间:2016-10-17 02:20:13

标签: yii2

我有自定义表单,我正在尝试编写自定义验证器,但它没有触发。每次按下提交按钮时,模型都会返回为有效:

class DeactivateForm extends Model {

    public $deactivate_reason;

    public function rules() {
        return [
            [ 'deactivate_reason', 'reasonValidator' ],
        ];
    }

    public function reasonValidator( $attribute, $params ) {
        $this->addError( 'deactivate_reason', 'Error !!!' );
    }

    public function attributeLabels() {
        return [
            'deactivate_reason' => 'Reason for deactivating',
        ];
    }
}

实际形式是简单的:

$form = ActiveForm::begin( [
    'id' => 'deactivate-form'
] );

在规则中使用[ 'deactivate_reason', 'required' ]时,所需规则正常,自定义规则仍会被忽略...

2 个答案:

答案 0 :(得分:0)

我不确定是否在空字段上强制运行验证,添加以下属性。

  

skipOnError => false和skipOnEmpty => false

[
  ['deactivate_reason', 'reasonValidator',  'skipOnError' => false,'skipOnEmpty'=>false],
]

答案 1 :(得分:0)

试试这个,添加如下的返回

public function reasonValidator( $attribute, $params ) {
   return $this->addError( 'deactivate_reason', 'Error !!!' );
}