yii2: rule Unique don't run


i am beginners with yii2 basic

to validate my form, i put rule unique on the field login but it doesn’t activate.

if i valide my form, the contrainst in data base declecnch error because the field is uniquein data base!

i want to do in form i have en error message that login already exist.


If you show us your code and where you are putting it, we will have a better chance of seeing what is going on…


my form and my rule

<?php $form = ActiveForm::begin([

‘method’ => ‘post’,

‘action’ => Url::to([‘registration/create’]),



<div class="form-group has-feedback">

&lt;?= &#036;form-&gt;field(&#036;model, 'lib_etab')-&gt;textInput(['maxlength' =&gt; true, 'class'=&gt;'form-control', 'placeholder' =&gt; '']) ?&gt;


&lt;?= &#036;form-&gt;field(&#036;model, 'alia_etab')-&gt;textInput(['maxlength' =&gt; true, 'class'=&gt;'form-control', 'placeholder' =&gt; '']) ?&gt;

&lt;?= &#036;form-&gt;field(&#036;model, 'adress_etab')-&gt;textInput(['maxlength' =&gt; true , 'class'=&gt;'form-control', 'placeholder' =&gt; '']) ?&gt;

&lt;?= &#036;form-&gt;field(&#036;model, 'fax_etab')-&gt;textInput(['maxlength' =&gt; true , 'class'=&gt;'form-control', 'placeholder' =&gt; '']) ?&gt;

&lt;?= &#036;form-&gt;field(&#036;model, 'logo_etab')-&gt;textInput(['maxlength' =&gt; true, 'class'=&gt;'form-control', 'placeholder' =&gt; '']) ?&gt;

 &lt;?= &#036;form-&gt;field(&#036;mail, 'ref_mail')-&gt;textInput(['maxlength' =&gt; true, 'class'=&gt;'form-control', 'placeholder' =&gt; '']) ?&gt;


&lt;?= &#036;form-&gt;field(&#036;tel, 'tel')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;

&lt;?= &#036;form-&gt;field(&#036;users, 'login')-&gt;textInput(['maxlength' =&gt; true]) ?&gt;

&lt;?= &#036;form-&gt;field(&#036;users, 'passwd')-&gt;passwordInput(['maxlength' =&gt; true]) ?&gt;

 &lt;?= &#036;form-&gt;field(&#036;users, 'confirm')-&gt;passwordInput(['maxlength' =&gt; true]) ?&gt;

&lt;div class=&quot;form-group&quot;&gt;

    &lt;?= Html::submitButton(&#036;model-&gt;isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' =&gt; &#036;model-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?&gt;


&lt;?php ActiveForm::end(); ?&gt;

public function rules()


    return [

        [['login', 'passwd', 'confirm', 'type_users', 'status', 'validation', 'authKey', 'accessToken'], 'required'],

		[['login'], 'unique', 'targetAttribute' =&gt; ['login']],

        [['type_users', 'status'], 'integer'],

        [['login'], 'string', 'min' =&gt; 3, 'max' =&gt; 20,  'message'=&gt; 'hello'],

        [['passwd', 'confirm'], 'string', 'min' =&gt; 6, 'max' =&gt; 128 ],

		[[ 'validation'], 'string', 'max' =&gt; 128],

		['confirm', 'compare','compareAttribute'=&gt;'passwd'],

        [['authKey', 'accessToken'], 'string', 'max' =&gt; 50]




I don’t see any real problems off hand…

But you are using a more complex rule line then you need to.

The layout you are using is for use when you have multiple fields

you need to check against multiple db columns…

I don’t know if that is really valid or not.

The guide shows these examples, but others may work ( such as yours… ), or may not…


    // a1 needs to be unique in the column represented by the "a1" attribute

    ['a1', 'unique'],

    // a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value

    ['a1', 'unique', 'targetAttribute' => 'a2'],

    // a1 and a2 need to be unique together, and they both will receive error message

    [['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']],

    // a1 and a2 need to be unique together, only a1 will receive error message

    ['a1', 'unique', 'targetAttribute' => ['a1', 'a2']],

    // a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)

    ['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']],


Try the simpler layout of:

    // a1 needs to be unique in the column represented by the "a1" attribute

    ['a1', 'unique'],



To get the nice neat code blocks like above click on the ‘<>’ tool in the tool bar,

then paste your code between the code tags that it generates…

I assume your rules are in your controller action…


I noticed that you have many models in your form, i.e., $model, $mail, $tel and $users.

Is $model something like "profile"?

And are you complaining that “unique” validator won’t display an appropriate error message when the user has tried to use an existing login name?

Then, please show your controller code, using the “code” tag :)

with a simpler form I noticed that when I put $model->save(), it happens to return the iformationn like what the field is unique for this model but with my example, i have many models, it lorque I call the save method, it does not go so I provided al removes it and suddenly it can not Return error for a unique field!

 public function actionCreate()


        $model = new Etablissement();

		$mail = new Mail();

	    $users = new Users();

	    $tel = new Telephone();

        $connection = \Yii::$app->db;





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

		$users->load(Yii::$app->request->post()) &&

		$mail->load(Yii::$app->request->post())  &&

		$tel->load(Yii::$app->request->post()) /*&&


		) {

		echo 'hello';

		//if ($users->validate()){

           $transaction = $connection->beginTransaction();


		 try {

		 $connection ->createCommand()

                              ->insert('users', [

									  'id_user' =>'',

									  'login' => $_POST['Users']['login'],

									  'passwd' =>md5($_POST['Users']['passwd']),

									  'confirm' =>md5($_POST['Users']['confirm']),

									  'type_users' =>'1',

									  'status' =>'0',

									  'validation' =>'TEST',

									  'authKey' =>'TEST',

									  'accessToken' =>'TEST',




						$stud = \app\models\Users::find()->max('id_user');

						//  echo $stud;




		   $connection ->createCommand()

                              ->insert('etablissement', [

									  'id_etab' =>"",

									  'lib_etab' =>$model->lib_etab,

									  'alia_etab' =>$model->alia_etab,

									  'adress_etab' =>$model->adress_etab,

									  'fax_etab' =>$model->fax_etab,

									  'logo_etab' =>$model->logo_etab,

									  'id_user' =>$stud,



						    $etab = \app\models\Etablissement::find()->max('id_etab');

			$connection ->createCommand()

                              ->insert('mail', [

                                      'id_mail' =>"",

									  'ref_mail' => $_POST['Mail']['ref_mail'],									                                      

									  'id_etab' =>$etab,




            $connection ->createCommand()

                              ->insert('telephone', [

                                      'id_tel' =>"",

									  'tel' => $_POST['Telephone']['tel'],									                                      

									  'id_etab' =>$etab,




You can do it like this:

        if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {

            $isValid = $user->validate();

            $isValid = $profile->validate() && $isValid;

            if ($isValid) {



                return $this->redirect(['user/view', 'id' => $id]);



Please read the following doc:


BTW, you don’t need to access raw $_POST.

And, why md5? You should use the security component of Yii.


thank, the problem with my model is $isValid = $user->validate() return false thus it is’nt enter in the condition! i don’t know why $isValid is false!