【问题标题】:How to validate both attribute together in Yii 1.x如何在 Yii 1.x 中同时验证两个属性
【发布时间】:2015-03-27 05:06:51
【问题描述】:

我在Yii1.x (1.1.14) 中遇到了问题,但我还没有找到解决方案。

在我的表单中,我有两个文本字段,[文本字段 A] 和 [文本字段 B]。我想一起验证他们两个遵循以下规则:

  1. 如果 A && B 为空,则返回 1 条需要的错误消息。
    例如:验证用户名和密码,其中一个不正确,为两者输出 1 条消息:您的用户名或密码不正确。
  2. 如果 A || B 可用,验证可用属性的数值。这也意味着如果两者都可用,则验证两者的数字。

我尝试使用自定义验证,但它验证了每个属性。因此,我无法同时验证它们。

有人知道这个问题的解决方案吗?

【问题讨论】:

  • Yii 没有字段组合的验证规则。所以我认为您需要手动验证并手动生成错误消息。

标签: php validation yii


【解决方案1】:

您可以编写自己的验证器。只需在模型中添加一个方法:

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return  array(
        'A',
        'requiredIf',
        'isSet' => 'B'
   );

/**
 * Validator-Rule
 * @param string $attribute 
 * @param array $params 
 */
public function requiredIf($attribute, $params){
    //validate
    $isSet = $params['isSet'];
    if(! empty($isSet)) {
        $attr = $this->{$isSet};
        $other = $this->{$attribute};
        if(! empty($attr) && empty($other)) {
            $this->addError($attribute, 'Error Text');
        }
    }
}

当 B 被设置,但 A 没有被设置时,这个验证器会抛出一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多