Answer the question
In order to leave comments, you need to log in
Is one of the two fields required Yii2?
Hello! The question is there are two fields phone and phone-other how to make one of the two fields required?
view
<?= $form->field($model, 'phone')->widget(MaskedInput::className(), [ 'mask' => ['+38 (999) 999-99-99'], 'options' =>['placeholder' => 'Мобильный номер телефона']])->label('Телефон *')->hint('для подтверждения и статусов заказа') ?>
<?= $form->field($model, 'phone_other')->textInput(['placeholder' => 'Другой номер телефона'])->label('Доп. телефон *')->hint('для подтверждения заказа') ?>
[['phone', 'phone_other'], 'required', 'when' => function ($model) {
$validate = empty($model->phone) && empty($model->phone_other);
if ($validate) { return false; }
return true;
}, 'whenClient' => "function (attribute, value) {
return $('#order-phone').val() == '' && $('#order-phone_other').val() == '';
}", 'message' => 'Необходимо заполнить хотя бы одно из полей "Телефон" или "Доп. Телефон"'],
Answer the question
In order to leave comments, you need to log in
Decided so.
[['phone', 'phone_other'], 'required', 'when' => function ($model) {
$validate = empty($model->phone) && empty($model->phone_other);
if ($validate) { return false; }
return true;
}, 'whenClient' => "function (attribute, value) {
if($('#order-phone').val() == '' && $('#order-phone_other').val() == ''){
$('.field-order-phone, .field-order-phone_other').addClass( 'has-error' ).find('.help-block-error').text( 'Необходимо заполнить хотя бы одно из полей «Телефон» или «Доп. Телефон»');
return true;
} else {
$('.field-order-phone, .field-order-phone_other').removeClass( 'has-error' ).find('.help-block-error').text('');
return false;
}
}", 'message' => 'Необходимо заполнить хотя бы одно из полей «Телефон» или «Доп. Телефон»'],
Logically, make the first field mandatory. The second is optional.
And so, one of the first links Google
public function rules()
{
return array(
// array('username, email', 'required'), // Remove these fields from required!!
array('email', 'email'),
array('username, email', 'my_required'), // do it below any validation of username and email field
);
}
public function my_required($attribute_name, $params)
{
if (empty($this->username)
&& empty($this->email)
) {
$this->addError($attribute_name, Yii::t('user', 'At least 1 of the field must be filled up properly'));
return false;
}
return true;
}
I will keep in the answers a simple example of validation by two fields =)
public function rules()
{
return [
[['phone', 'phone_other'], 'required', 'when' => function($model) {
return (!$model->phone && !$model->phone_other);
},'whenClient' => 'function(){return false;}',
/*'whenClient' => 'function (attr, value) {
return $("#MODEL-phone").val() == "" && $("#MODEL-phone_other").val() == "";
}', 'message' => 'Заполните "Телефон" или "Доп. Телефон"'*/],
//...
];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question