garima
garima

Reputation: 31

Yii2 : - Require one error message for three fields

I have three dropdowns for day, month, and year. when I applied required condition yii2 validation show individual error for all three fields. But I want single error message for three fields like "dob is required".

view file :

<?= $form->field($model, "month")->dropDownList([], ['class'=>'form-control day'])->label(false);?>
<?= $form->field($model, "day")->dropDownList([], ['class'=>'form-control day'])->label(false);?>
<?= $form->field($model, "year")->dropDownList([], ['class'=>'form-control year'])->label(false);?>

model :

public $day;    
public $month;
public $year;

[['month','day','year'], 'required', 'when' => function ($model) {
    return (($model->month == "") || ($model->day == "") || ($model->year == ""));
    }, 
    'whenClient' => "function (attribute, value) {
    return ($('#user-month').val() == '' || $('#user-day').val() == '' || $('#user-year').val() == '');
    }",'on'=>'profile'
]

This code showing me error messages for all three dropdowns individually. But i want single error message for dob: like "dob is required".

Upvotes: 1

Views: 713

Answers (2)

Lesser Jank
Lesser Jank

Reputation: 381

Maybe You sholud do something more like:

['month', 'validationFunction', 'skipOnEmpty' => false]
...
public function validationFunction($attribute, $params) {
    if( !$this->hasErrors() ) {
        if (!$this->month || !$this->day || !$this->year) {
            $this->addError($attribute, 'dob is required');
        }
    }    
}

Upvotes: 0

Yasin Patel
Yasin Patel

Reputation: 5731

Try this :

Write this code in your Model :

public function rules()
 {
     return [
         [['month','day','year',],'required','on'=>['create','update'],'message' => 'Please enter DOB.'],
       ];
 }

Write this code in your Action in Controller where you call your view:

 $model = new YourModelName();
 $model->scenario = "create";

Example :

 $model = new User();
 $model->scenario = "create";

Upvotes: 1

Related Questions