Conditional validation doesn't work on resubmit


(Kokosm) #1

I have a conditional field client side validation enabled - basically containerPrice is required if the value of radio button isContainerInlcluded equals to 1.

Validation rules

public function rules()
{
    return [
            [['monthlyTakeawayOrders', 'isContainerIncluded'], 'required'],
            ['containerPrice', 'required', 'when' => function($model){
                return $model->isContainerIncluded;
                }, 'whenClient' => "function(attribute, value) {
                    return $('#pricingform-iscontainerincluded input:checked').val() == 1;
                }"
            ],
            [['monthlyTakeawayOrders', 'containerPrice'],'integer']

    ];
}

The form

<?php $form = ActiveForm::begin(['id' => 'pricing-form']); ?>

                <?= $form->field($pricingForm, 'monthlyTakeawayOrders') ?>

                <?= $form->field($pricingForm, 'isContainerIncluded')->radioList([
                        0 => 'Option 0',
                        1 => 'Option 1'
                ]) ?>

                <?= $form->field($pricingForm, 'containerPrice') ?>

                <div class="form-group">
                    <?= Html::submitButton('Calculate', ['class' => 'btn btn-primary', 'name' => 'pricing-button']) ?>
                </div>

            <?php ActiveForm::end(); ?>

In most cases, it works just fine but when I submit the form with isContainerInlcluded on 0, then switch it to 1 and submit again (without filling containerPrice), the validation is not triggered and form is submitted, eventhough containerPrice should be required.

In addition, after performing the steps above, if I focus on the containerPrice field and then submit, error message is displayed but the form is submitted anyway.

The form is sort of a price calculator and I submit it through ajax, so there is no page refresh performed after submit as it is required that user can change their input and resubmit the form again to see instant results.

I don’t know why this is happening, so any help is appreciated. Thanks!