Yii框架验证规则


Yii framework validation rules

我的项目使用Yii 1。我在一张表格中有5个字段,必须填写。这并没有问题——模型中有一个简单的验证规则。但是,还有一个字段是不需要的。但如果已填充,则必须不需要其他5个字段。我应该如何在模型中的rules()方法中定义这样的验证规则?

提前非常感谢!

尝试使用场景。验证数据时,请检查此字段是否已填充,并创建具有特定场景的新模型。

查看此处

您可以创建自己的自定义验证规则,这样您就可以跳过场景,您需要:

声明:

$model->TRIGGERATTR = is the attribute that if informed is going to indicate that the other 5 are required
$model->ATTR1 = one of the five other attributes 
$model->ATTR2 = two of the five other attributes
.
.
. and so on...
  1. 在模型中声明规则,如下所示:array('ATTR1, ATTR2, ATTR3, ATTR4, ATTR5','{NameofRule}Validator'),

  2. components/validators/general/{NameofRule}Validator 中创建自定义验证

    带有以下代码

class {NameofRule}Validator extends CValidator { public function validateAttribute($model, $attribute) { if((isset($model->TRIGGERATTR))&&(!is_null($model->TRIGGERATTR)) { if(!isset$model->$attribute||is_null($model->$attribute)) { $this->addError($model, $attribute, 'Is not Informed and it should be'); } } } }

不要忘记添加您的评论并标记为已解决;-)