【问题标题】:Yii framework validation rulesYii 框架验证规则
【发布时间】:2015-02-09 09:56:46
【问题描述】:

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

非常感谢您!

【问题讨论】:

  • 欢迎来到stackoverflow,如果你能发布你所说的规则会有所帮助。

标签: php validation yii frameworks rules


【解决方案1】:

尝试使用场景。当你验证你的数据时,检查这个字段是否被填写并创建一个具有特定场景的新模型。

看here

【讨论】:

    【解决方案2】:

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

    声明:

    $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'); } } } }

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多