Compare rule yii2 doesn't work correctly - php

I have my rules method like this:
public function rules()
{
return [
[['username', 'email', 'password'],'filter', 'filter' => 'trim'],
[['username', 'email', 'password'],'required', 'message' => '{attribute} can not be empty'],
['username', 'string', 'min' => 2, 'max' => 255],
['password', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'required', 'message' => 'This field can not be empty'],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match", 'skipOnError' => true],
['username', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
['email', 'email'],
['email', 'unique',
'targetClass' => User::className(),
'message' => 'This name is already used.'],
];
}
And my view code is like this:
<?php $form = ActiveForm::begin(['action' => 'login/register']); ?>
<?= $form->field($registration, 'username',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_username', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'password',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'password_repeat',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['id' => 'register_password_repeat', 'class' => 'md-input']) ?>
<?= $form->field($registration, 'email',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->textInput(['id' => 'register_email', 'class' => 'md-input']) ?>
<div class="uk-margin-medium-top">
<button class="md-btn md-btn-primary md-btn-block md-btn-large">Sign in</button>
</div>
<?php ActiveForm::end(); ?>
When I'm filling all given fields I have an error Passwords don't match when repeat the password even when it's correct at first time. Is there something with my validation rules or is it a bug in Yii Validator?
UPD: I've tried 'skipOnError' => true. I found it as an answer for the similar question but it still doesn't work as it's expected.
UPD: I did some validation in my console:
var a = $('#register_password')
undefined
a.val()
"Halloha"
var b = $('#register_password_repeat')
undefined
b.val()
"Halloha"
But it still shows Passwords don't match error message

try using the rule like this
// validates if the value of "password" attribute equals to that of
['password', 'compare', 'message'=>"Passwords don't match"],
it automatically compares the password value to attribute password_repeat instead of doing it in the other order as explained in the documentation .
http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#compare

Try avoid the id in password input (the id is automatically generated by yii2)
<?= $form->field($registration, 'password',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput(['class' => 'md-input']) ?>
<?= $form->field($registration, 'password_repeat',
['template' => '<div class="uk-form-row">
{input}{error}
</div>'])
->passwordInput([ 'class' => 'md-input']) ?>

Related

Yii 2 Kartik input validation message is coming while clicking the browse button only

<?php use kartik\file\FileInput;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'id' => 'import-pdf',
'options' => ['enctype' => 'multipart/form-data'],
]); ?>
<?=
$form->field($model, 'file_name')->widget(FileInput::classname(), [
'options' => ['multiple' => false],
'pluginOptions' => [
'showPreview' => false,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false,
],
]);
?>
//file_name is the attribute I'm using it
public function rules()
{
return [
[['file_name'], 'required'],
[['status', 'total_pages', 'processed_pages', 'file_type'], 'safe'],
[['total_pages', 'processed_pages', 'file_type'], 'integer'],
[['file_name'], 'file', 'skipOnEmpty' => true, 'extensions' => 'pdf'],
[['status'], 'string', 'max' => 255],
];
}
File name cannot be blank message is coming while clicking browse button only, It should show the validation message after selecting the file only
https://i.stack.imgur.com/GuENh.png
Have you tried to assign to $file_name the uploadedFile instance before the validation?
$model->file_name = UploadedFile::getInstance($model, 'file_name');
or
$model->file_name = UploadedFile::getInstanceByName('nameOfTheField');

email unique validator yii2 doesn't return message validation

I am try to use unique validator for email in my model, but it doesn't work.. i mean no notification that display in form when user input the same email that already saved in db and user still can click submit button(and page reloaded) eventhough data isn't saved in db. What's wrong with my code?
this is my model validation:
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\application\common\models\User', 'message' => 'This email address has been taken.'],
this is my form :
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model,'email')->textInput()->input('email', ['placeholder' => "Email"])->label(false) ?>
...
<div class="form-group">
<?= Html::submitButton('SIGN UP NOW', ['class' => 'btn btn-sign', 'type' => 'submit']) ?>
</div>
<?php ActiveForm::end(); ?>
and this is my model to process save:
if (!$this->validate()) {
return null;
}
$user = new User();
$user->email = $this->email;
...
you should add a filter in your model validation.
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique',
'targetClass' => '\common\models\User',
'message' => Yii::t('frontend', 'This email address has already been taken.')
],

Yii2 making checkbox required doesn't work

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.
Remove the compare rule and update the required rule as shown below.
[['check'], 'required', 'requiredValue' => 1, 'message'=>'bla-bla-bla'],
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],

captcha doen't validate in yii2

tips : username and email is check by ajaxValidation with validate method.
all is correct but i guess captcha is changed in server but the old picture is in client.
i googling alot no result found.
this is view:
<?php
$form = \yii\widgets\ActiveForm::begin([
'id' => 'form-signup',
'action' => 'signup',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
'validationUrl' => 'validation',
'validateOnBlur' => true,
'fieldConfig' => [
'template' => '<div class="col-md-4" >{label}{input}{error}</div>'
]
]);
?>
<?= $form->field($signup, 'username', ['enableAjaxValidation' => true]) ?>
<?= $form->field($signup, 'name') ?>
<?= $form->field($signup, 'family') ?>
<?= $form->field($signup, 'mobile') ?>
<?= $form->field($signup, 'password')->passwordInput() ?>
<?= $form->field($signup, 'password_repeat')->passwordInput() ?>
<?= $form->field($signup, 'email', ['enableAjaxValidation' => true]) ?>
<?= $form->field($signup, 'verifyCode', ['enableAjaxValidation' => false])->widget(yii\captcha\Captcha::className()) ?>
<div class="form-group">
<?= yii\helpers\Html::submitButton('signup', ['class' => 'btn btn-green margin-right', 'name' => 'signup-button']) ?>
</div>
controller:
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
} else {
;
\yii\widgets\ActiveForm::validate($model);
}
} else {
return $this->render('/partials/_signup', ['signup' => $model]);
}
ajax validation controller method:
public function actionValidation() {
$model = new SignupForm();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
}
model:
public $name;
public $family;
public $mobile;
public $username;
public $email;
public $password;
public $password_repeat;
public $verifyCode;
public function rules() {
return [
[['name', 'family', 'mobile'], 'default'],
['name', 'string', 'max' => 50],
['family', 'string', 'max' => 50],
['mobile', 'string', 'max' => 11],
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'string', 'min' => 2, 'max' => 255],
[['username'], 'unique', 'targetClass' => '\frontend\models\User', 'message' => 'username already taken.'],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\frontend\models\User', 'message' => 'email name already taken.'],
['password', 'required'],
['password', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'string', 'min' => 6, 'max' => 255],
['password_repeat', 'compare', 'compareAttribute' => 'password'],
['verifyCode', 'captcha'],
];
}
there is no behaviour in controller
enableAjaxValidation of a form takes precedence over that of a field, so it's hard to tell what exactly you are trying to do with your current settings
Make sure you have verifyCode declared as an attribute on your model
Captcha verification code is saved in the session. The session key is a combination of controller's and action's ids. So you might have a misconfigured session. Or your captcha's action name is not 'captcha', - you are missing that part of your source code in the question.

Yii2, Custom validation message with attribute names

In Login form, I need to have glyphicon-remove icon at the end of every validation message with the corresponding field names. So I used below code in the Login model.
['email', 'required', 'message' => 'Email cannot be blank<span class="glyphicon glyphicon-remove"></span>'],
['password', 'required', 'message' => 'Password cannot be blank<span class="glyphicon glyphicon-remove"></span>']
Instead of this above code, Is there any possible way to use something like the below code.
[['email', 'password'], 'required', 'message' => $attribute.' cannot be blank<span class="glyphicon glyphicon-remove"></span>']
The idea of the above code is to get corresponding field name dynamically for every fields.
Please do the needful. Thanks.
Update
The HTML code (<span class="glyphicon glyphicon-remove"></span>) here I've used is output correctly by using encode=>'false'. But what I need is instead of defining separately for every fields, need to define commonly for all fields.
You can use {attribute} in your message to reference the attribute name.
public function rules()
{
return [
[
['email','password', 'password_verify', 'alias', 'fullname'],
'required',
'message' => '{attribute} is required'
],
[['email'], 'email'],
[['fullname'], 'string', 'max' => 50],
[['password', 'password_verify'], 'string', 'min' => 8, 'max' => 20],
[['password_verify'], 'compare', 'compareAttribute' => 'password'],
];
}
You can also use the other options set in the validator like {min} or {requiredValue}
Add this in your form:
_form.php
<?php
$form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'],
'fieldConfig' => ['errorOptions' => ['encode' => false, 'class' => 'help-block']]
]);
?>
errorOptions default encoding is true so, your html code is encoded as message, so it won't work until you set 'encode' => false.

Categories