dongqiang5932 2017-04-07 03:31
浏览 18
已采纳

验证规则与模型场景冲突yii

I have validation rules for model as follows

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    //post of step 1
    if (isset($_POST['yt0']))
    {
        return array(
                array('EmailAddress,', 'required','message' =>  Yii::t('message', 'USERNAME_REQUIRED')),
                array('Password,', 'required','message' =>  Yii::t('message', 'PASSWORD_REQUIRED')),
                array('confirmPassword,', 'required','message' => Yii::t('message', 'CONFIRM_PASSWORD_REQUIRED')),
                array('Password','length', 'max' => 100, 'min' => 6, 'tooShort' => Yii::t('message', 'PASSWORD_LENGTH')),
                array('confirmPassword', 'compare', 'compareAttribute'=>'Password','message' => Yii::t('message', 'PASSWORD_COMPARE')),
                array('EmailId,', 'required','message' => Yii::t('message', 'EMAILID_REQUIRED')),
                array('EmailId','email','message'=>Yii::t('message', 'EMAILID_VALID')),
                array('chapterCode,', 'required','message' => Yii::t('message', 'CHAPTERCODE_REQUIRED')),
                array('verifyCode,', 'required','message' =>Yii::t('message', 'VERIFYCODE_REQUIRED')),
                array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'caseSensitive'=>true,'message' =>Yii::t('message', 'VERIFYCODE_INCORRECT') ),
                array('EmailAddress', 'unique','className'=>'User','attributeName'=>'EmailAddress','message'=>Yii::t('message', 'EMAILID_UNIQUE')),
                array('PersonId', 'unique','className'=>'User','attributeName'=>'PersonId','message'=>"Person already exists."),
                array('FailedLoginCount', 'safe'),
        );
    }   elseif (isset($_POST['yt1']))
    {
        return array(
                array('EmailAddress,', 'required','message' => Yii::t('message', 'USERNAME_REQUIRED')),
                array('Password,', 'required','message' =>  Yii::t('message', 'PASSWORD_REQUIRED')),
                array('FailedLoginCount', 'safe'),

        );
    }elseif (isset($_POST['savecontact'])||$this->memBelongsto==0)
    {
        return array(
                array('EmailAddress,', 'required','message' => Yii::t('message', 'USERNAME_REQUIRED')),
                array('Password,', 'required','message' =>  Yii::t('message', 'PASSWORD_REQUIRED')),
                array('confirmPassword', 'required','message' => Yii::t('message', 'CONFIRM_PASSWORD_REQUIRED')),
                array('Password','length', 'max' => 100, 'min' => 6,'tooShort' => Yii::t('message', 'PASSWORD_LENGTH')),
                array('confirmPassword', 'compare', 'compareAttribute'=>'Password','message' => Yii::t('message', 'PASSWORD_COMPARE')),
                array('EmailId,', 'required','message' => Yii::t('message', 'EMAILID_REQUIRED'),'except'=>'datavalid'),
                array('EmailId','email','message'=>Yii::t('message', 'EMAILID_VALID'),'except'=>'datavalid'),
                array('FailedLoginCount', 'safe'),

        );
    }else{
        return array(
                array('EmailAddress,EmailId, Password', 'required'),
                array('PersonId, ActiveFlag, FailedLoginCount', 'numerical', 'integerOnly'=>true),
                array('EmailAddress, Password', 'length', 'max'=>100),
                array('confirmPassword,', 'required','message' => Yii::t('message', 'PASSWORD_REQUIRED')),
                array('Password','length', 'max' => 100, 'min' => 6, 'tooShort' => Yii::t('message', 'PASSWORD_LENGTH')),
                array('confirmPassword', 'compare', 'compareAttribute'=>'Password','message' => Yii::t('message', 'PASSWORD_COMPARE')),
                array('chapterCode,', 'required','message' => Yii::t('message', 'CHAPTERCODE_REQUIRED')),
                array('verifyCode,', 'required','message' =>Yii::t('message', 'VERIFYCODE_REQUIRED')),
                array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'caseSensitive'=>true,'message' =>Yii::t('message', 'VERIFYCODE_INCORRECT')),
                array('FailedLoginCount', 'safe'),
        );
    }
}

and here yt0 is name of submit button on signup page and so for signup the rules of yt0 will be applied and I have another form for change password so on that page I need only three fields and the submit button for change password is savecontact and but savecontact rules are applied but the signup button rules are conflicting so the validation on signup is not working . Is it right way to right rules as above any suggestions please....

展开全部

  • 写回答

1条回答 默认 最新

  • dsp15140275697 2017-04-09 02:13
    关注

    while this may work, you are doing it in the wrong approach. You should use scenario to perform these kind of tasks.

    First of all, you can declare scenarios for your different forms:

    class User extends ActiveRecord
    {
        const SCENARIO_LOGIN = 'login';
        const SCENARIO_SIGNUP = 'signup';
        const SCENARIO_UPDATE = 'update';
    }
    

    When you are done with defining scenarios, you can tell your model what attributes to use for massive assignment and apply validation for the specific scenarios.

    class User extends ActiveRecord
    {
        const SCENARIO_LOGIN = 'login';
        const SCENARIO_REGISTER = 'register';
        const SCENARIO_UPDATE = 'update';
    
        public function scenarios()
        {
            return [
                self::SCENARIO_LOGIN => ['username', 'password'],
                self::SCENARIO_REGISTER => ['email', 'username', 'password'],
                self::SCENARIO_UPDATE => ['email', 'username', 'password'],
            ];
        }
    }
    

    Now that you are done, you can choose to add validation rules or use the default one generated by gii.

    class User extends ActiveRecord
    {
        const SCENARIO_LOGIN = 'login';
        const SCENARIO_REGISTER = 'register';
        const SCENARIO_UPDATE = 'update';
    
        public function scenarios()
        {
            return [
                self::SCENARIO_LOGIN => ['username', 'password'],
                self::SCENARIO_REGISTER => ['email', 'username', 'password'],
                self::SCENARIO_UPDATE => ['email', 'username', 'password'],
            ];
        }
    
        public function rules()
        {
            return ArrayHelper::merge([
                ['email' => 'email', 'message' => Yii::t('message', 'wrong email format')],
                [['email', 'password', 'username'] => 'email'],
                ['username', 'exist', 'on' => self::SCENARIO_LOGIN], // this will apply only on login
                // other rules
            ], parent::rules());
        }
    }
    

    Now that you are done with your model scenarios and rules, time to use them correctly.

    Head to your controller and instantiate your models using the scenarios:

    public function actionLogin()
    {
        $model = new User(['scenario' => User::SCENARIO_LOGIN]);
    
        if($model->load(Yii::$app->request->post())) {
            // $model will have username and password even if email is in the form since it is using
            // User::SCENARIO_LOGIN
            $model->validate(); 
            // will validate only username and password even if email is in the form
            // will also use the username exist validator
            // do your stuff
        }
    }
    
    public function actionRegister()
    {
        $model = new User(['scenario' => User::SCENARIO_REGISTER]);
    
        if($model->load(Yii::$app->request->post())) {
            // $model will have username, password and email
            $model->validate(); 
            // will validate email, username and password but will not use the
            // username exist validation rule since it has the `'on' => self::SCENARIO_LOGIN`
            // do your stuff
        }
    }
    

    Go to http://www.yiiframework.com/doc-2.0/guide-structure-models.html for more details about how to properly use models and validations

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部