Model validation on required


I have a login form. there a user can login by using email or mobile number. but my conditions is that is if API available then user can login by using mobile number other wise user can login by using email. As per my conditions my login form always have one option either mobile number or email.

in my model validation

public function rules()


    return array(

        array('email, password, mobile_number', 'required'),

        // password needs to be authenticated

        array('password', 'authenticate'),

        array('email', 'email'),




if user login by email it always check mobile number require. in same way if user login by mobile it always check email require.

please help me, how could i add required validation by using conditions.



It sounds like you want scenario-based validation

class MyModel extends \yii\base\Model {

    const SCENARIO_MOBILE = 'mobile_login';

    const SCENARIO_EMAIL = 'email_login';

    public function scenarios () {

    	$scenarios = parent::scenarios();

    	$scenarios[self::SCENARIO_MOBILE] = ['mobile_number'];

    	$scenarios[self::SCENARIO_EMAIL] = ['email', 'password'];

    	return $scenarios;


    public function rules() {

        return [

            [['email','password','mobile_number'], 'required'],

            [['email'], 'email'],

            [['password'], 'authenticate'], // password authentication



    public function login() {

        if($this->validate()) {

            return Yii::$app->user->login($this->getUser());


        return false; // login failed


    public function getUser() {

        // Get and return the user with an Active Record from here



Then in your controller whatever you’re doing to determine the login fields you would set the scenario to use

class SiteController extends \yii\web\Controller {

    public function login() {

        // you may want to use some condition to determine the scenario

        $model = new MyModel(['scenario' => MyModel::SCENARIO_MOBILE]); // will validate only mobile number


        if($model->load(Yii::$app->request->post()) && $model->login())) {

           // log in success

           return $this->goBack();


        return $this->render('login', ['model' => $model]);