我有三个下降日,月和年。当我申请所需条件时yii2验证显示所有三个字段的个别错误。但我想要三个字段的单个错误消息,如“dob is required”。
查看文件:
<?= $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);?>
模特:
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'
]
此代码单独显示所有三个下拉列表的错误消息。但是我想要dob的单个错误消息:例如“dob is required”。
答案 0 :(得分:1)
试试这个:
将此代码写入模型:
public function rules()
{
return [
[['month','day','year',],'required','on'=>['create','update'],'message' => 'Please enter DOB.'],
];
}
将此代码写入控制器中的操作,并在其中调用视图:
$model = new YourModelName();
$model->scenario = "create";
示例:
$model = new User();
$model->scenario = "create";
答案 1 :(得分:0)
也许你sholud做更像的事情:
['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');
}
}
}