yii2 conditional validation is not working serverside?

895 views Asked by At

I am using username field in form,i set rule like below.

['username', 'required','when' => function($model) {
            return $model->pin == true;
        }],

(i.e)when the property pin goes true that time only i need username field required,all are working fine in clientside,but this validation falis on serverside,what is wrong on my code.

UPDATE:

controller code

public function actionTest()
{
    $model = new Test();
    if ($model->load(Yii::$app->request->post()) && $model->customValidation()) {
        if($model->validate())
        {
            //
        }
    } 
    return $this->render('testView', [
    'model' => $model,
    ]);
}

model

public $username;
public $pin = false;
public function rules()
{
 return [
    ['username', 'required','message' => 'You must enter username','when'      => function($model) {
        return $model->pin == true;
    }],
];
}
public function customValidation()
{
if()
{
    $this->pin = true;
    return false;
}
else
{
    return true;
}
}

view

if($model->pin)
{
<?= $form->field($model, 'username')->textInput(); ?>
}
1

There are 1 answers

6
Bizley On

You need to add whenClient for this to work on the client side:

[
    'username', 'required', 
    'when' => function ($model) {
        return $model->pin == true;
    },
    'whenClient' => "function (attribute, value) {
        // JS condition here
    }"
],

where JS condition depends on the DOM structure you have got. For example if pin property is checkboxed with id pin this can be:

'whenClient' => "function (attribute, value) {
    return $('#pin').is(':checked');
}"

UPDATE:
If you just set pin property in model you can modify the validation rule like that:

public function rules()
{
    $rules = [
        // other validation rules
    ];
    if ($this->pin) {
        $rules[] = ['username', 'required'];
    }
    return $rules;
}