Php Yii模型验证

Php Yii模型验证,php,validation,yii,Php,Validation,Yii,嘿,有人能帮我验证yii中的模型吗 class MyFormModel extends FormModel { public myAttribute1; public myAttribute2; public function __construct() { $this->myAttribute1 = 'blablabla' $this->user = n

嘿,有人能帮我验证yii中的模型吗

class MyFormModel extends FormModel
{
        public myAttribute1;
        public myAttribute2;

        public function __construct()
        {
                $this->myAttribute1 = 'blablabla'
                $this->user = new User();
        }

        public function rules()
        {
                $rules = parent::rules()
                $rules[] = array('myAttribute1', 'required', 'message' => 'this is required');
                $rules[] = array(#i need to add validation for $user->firstname here#);
                return $rules;
        }

}

如何验证另一个模型中的属性?

您可以在用户模型本身中编写firstname属性的规则。在此页面上,您可以使用

$userMDl = new User();
if($userMDl->validate(array('firstname ')) 
     // valid
}

您可以添加到
MyFormModel
属性中

private $firstname;
重写
init
方法

public function init(){
    ...
    $this->firstname = $user->firstname;
}
在您的
规则中

$rules[] = array('firstname', 'required', 'message' => 'firstname is required');

您可以在form类中编写自己的验证函数。请参阅下一篇文章:

您需要什么样的验证?我需要在名字上使用相同的“必需”…我尝试了$rules[]=array('user.firstname'、'required'、'message'=>'这是必需的');但是,将属性添加到此模型(如
public MyOtherAttribute)不起作用然后在规则中添加如下内容:
$rules[]=array('myAttribute1,MyOtherAttribute','required','message'=>'这是required')。这将在同一模型中验证该属性。通过此操作,您可以将属性从其他模型带到要验证的此模型,然后可以将此值传递给其他模型并保存其他模型。我希望你明白我的意思。我知道你的意思,但问题是如果我使用许多模型,每个模型都有大约5个属性,那么我的formmowal将有太多属性,这就是我这样做的原因。我需要对我以这种方式遇到的每个属性进行单独的验证,但是让我们说,在一个特定的地方,我需要对firstname进行验证,以一种格式,在另一个地方,我需要它以另一种格式,我该如何做??如果我能在我的formmodel中实现以下功能,我会更愿意:/