问题
This is my form:
<?php $form = ActiveForm::begin(); ?>
<?php echo $form->field($invite, 'email')->textInput([
'id' => 'register-email',
'placeholder' => Yii::t('UserModule.views_auth_login', 'email')]);
?>
<?php echo $form->field($invite, 'check')->checkbox([
'id' => 'check',
'uncheck' => null])->label(
Yii::t('UserModule.views_auth_login', 'I have read and accept') . ' <a href="#">'
. Yii::t('UserModule.views_auth_login', 'Terms & Conditions') . '</a> '
. Yii::t('UserModule.views_auth_login', 'and')
. ' <a href="#">' . Yii::t('UserModule.views_auth_login', 'Privacy Policy')
. '</a>' . '.');
?>
<hr>
<?php
echo \humhub\widgets\AjaxButton::widget([
'label' => Yii::t('UserModule.views_auth_login', 'Register'),
'ajaxOptions' => [
'type' => 'POST',
'beforeSend' => new yii\web\JsExpression('function(){ setModalLoader(); }'),
'success' => 'function(html){ $("#globalModal").html(html); }',
'url' => Url::to(['/user/auth/login']),
],
'htmlOptions' => [
'class' => 'btn btn-primary', 'id' => 'registerBtn'
]
]);
?>
<?php ActiveForm::end(); ?>
rules:
public function rules()
{
return [
[['email'], 'required'],
[['email'], 'unique'],
[['email'], 'email'],
[['email'], 'unique', 'targetClass' => \humhub\modules\user\models\User::className(), 'message' => Yii::t('UserModule.base', 'E-Mail is already in use! - Try forgot password.')],
[['check'], 'required'],
[['check'], 'compare', 'compareValue' => 1, 'message'=>'bla-bla-bla'],
];
}
How do I do my form valid only if both 'email' is not empty an valid and 'check' is checked? Now the issue is 'check' does not validate. Thanks.
回答1:
Remove the compare
rule and update the required rule as shown below.
[['check'], 'required', 'requiredValue' => 1, 'message'=>'bla-bla-bla'],
回答2:
Try the following:
Add this method in your model:
public function validateCheckWithEmail($attribute, $params)
{
if (empty($this->check) && !empty($this->email) && $this->validateAttribute($this, 'email')) {
$this->addError($attribute, $this->getAttributeLabel($attribute).' field cannon be empty.');
}
}
In your rules add:
[['check'], 'validateCheckWithEmail', 'skipOnEmpty' => false, 'skipOnError' => false],
来源:https://stackoverflow.com/questions/39338454/yii2-making-checkbox-required-doesnt-work