yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.24k stars 6.91k forks source link

Selectbox validation (required ) is skipped on empty #17683

Open mmezzawi opened 4 years ago

mmezzawi commented 4 years ago

What steps will reproduce the problem?

A form that contain an input and select box which will be populate based on the content of the input. if the input is numeric the select box will contain arithmetic operation else it will contain alphanumeric operation. Scenario : Input is empty , validation is triggered manually not while submitting the form.

What is the expected result?

Select box should be validated as required.

What do you get instead?

Select box validation is skipped when no option is available.

Additional info

There is should be a parameter to indicate if we should skip the validation when empty same as server side validation.

Q A
Yii version 2.0.30
PHP version 7
Operating system Windows
yii-bot commented 4 years ago

Thanks for posting in our issue tracker. In order to properly assist you, we need additional information:

Thanks!

This is an automated comment, triggered by adding the label status:need more info.

alex-code commented 4 years ago

Empty selects are treated as being valid, https://github.com/yiisoft/yii2/blob/master/framework/assets/yii.activeForm.js#L334

One way round,

// Model
public function rules()
{
  return [
    ['attribute', 'compare', 'compareValue' => 0, 'operator' => '!=', 'message' => '{attribute} is required.'],
  ];
}

// Form
$form->field($model, 'attribute')->dropDownList(['Please Select']);
samdark commented 4 years ago

It looks like an incorrect behavior but it seems to be specifically coded for that case. Need to find the reason. Likely it's somewhere in commits history...

alex-code commented 4 years ago

https://github.com/yiisoft/yii2/commit/c59df914c1f544889eafc4d8aa64132ae1337102#diff-3096f348a33d8aa1d79ebe62e5e0f304

samdark commented 4 years ago

I wonder if we can fix it for both use-cases...

alex-code commented 4 years ago

It is a bit confusing, the changelog mentions it was for checkboxlist validation but the code checks selects?

Maybe it should be removed. As it's checking values I don't think it should be in the ActiveForm js either.

alex-code commented 4 years ago

As it's the same section of code this bug could be fixed too, https://github.com/yiisoft/yii2/issues/17584

kadyrleev commented 4 years ago

Does look similar to this one: https://github.com/yiisoft/yii2/issues/17147