Closed raphaelsoul closed 7 years ago
I revised your code as below for my situation:
public function validateAttribute($model, $attribute) { $attributes = is_array($this->in) ? $this->in : preg_split('/\s*,\s*/', $this->in, -1, PREG_SPLIT_NO_EMPTY); $values = []; $chosen = 0; foreach ($attributes as $attributeName) { $value = $model->$attributeName; $attributesListLabels[] = '"' . $model->generateAttributeLabel($attributeName) . '"'; // TODO simplify this $chosen += !empty($value) ? 1 : 0; if ($value) { array_push($values,$value); } } if (!$chosen || $chosen < $this->min) { $attributesList = implode(', ', $attributesListLabels); $message = strtr($this->message, [ '{min}' => $this->min, '{attributes}' => $attributesList, ]); $model->addError($attribute, $message); } if (!(count($values) == 1)){ $model->addError($attribute,'only one of ' . implode(', ', $attributesListLabels) . 'can be filled.'); } }
The usage situation Example is: only attr1 and attr2 is aceptable. when both provided. add erro to the model.
attr1
attr2
Maybe you can make an enhancement for this situation, and make it configurable?
@raphaelsoul, If I got you, you should use conditional validation when to achieve this. By the way, could you show your use case for this? (thanks for your contribution)
when
I revised your code as below for my situation:
The usage situation Example is: only
attr1
andattr2
is aceptable. when both provided. add erro to the model.Maybe you can make an enhancement for this situation, and make it configurable?