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.
Related
I am working on yii2.
I have a below field in my _form
$form->field($model, 'area_name')
->widget(Select2::className(),[
'data' => \common\models\AllowArea::toAreaArrayList(),
'options' => ['placeholder'=>'Select Area'],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true
],
]);
?>
When I am trying to select from it I am getting
Area Name must be a string.
GUI
Below is my validation rule
public function rules()
{
return [
[['user_id','created_by','updated_by'], 'integer'],
[['area_name','user_id','salesman_code','city_name'], 'required'],
[['area_code', 'user_name'], 'string', 'max' => 50],
[['created_at'],'safe'],
[['area_name', 'salesman_code', 'salesman_name'], 'string', 'max' => 100],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
Function
public static function toAreaArrayList()
{
$sds = Yii::$app->sds->createCommand("Select * from Area")->queryAll();
return ArrayHelper::map(Yii::$app->sds->createCommand("select distinct AreaNameFull from Area where AreaCode NOT IN ('020201001','020202001')")->queryAll(),'AreaNameFull',function($sds, $defaultValue){
return $sds['AreaNameFull'];
});
}
Any help would be highly appreciated.
I just removed area_name from [['area_name', 'salesman_code', 'salesman_name'], 'string', 'max' => 100], to [[ 'salesman_code', 'salesman_name'], 'string', 'max' => 100], and it's start working.
Select 2 widget initializes in multiple mode. That means that the result is an array.
If it's not desired behavior, just remove 'multiple' => true.
Otherwise, the field rule of the form should be
['area_name', 'each', 'rule' => ['string', 'max' => 100]],
<?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');
I'm trying to validate a unique entry in my laravel app
following is my validation array,
$website = $websiteModel->find($id);
$this->validate($request, [
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
], $request->all());
My validation working properly BUT,
When i tried to enter a duplicate value for my domain field, It get validated properly but not showing the error message, saying sorry the name is already exists...
<input type="text" id="domain" class="form-control" name="domain" >
{!! $errors->first('domain', '<span class="help-block" role="alert">:message</span>') !!}
Here in this span it shows nothing but in the common error message area it shows sorry the form cannot be updated... So how can I validate the field properly and display the relevant error message
Do something like this:
On insert request use
'domain' => [
...
'unique:websites,domain'
]
On update request use
'domain' => [
...
"unique:websites,domain,{$this->website->id}"
]
Or
'domain' => [
...
Rule::unique('websites', 'domain')->ignore($this->website)
]
You passed $request->all() as validation messages.
Please Try:
$website = $websiteModel->find($id);
$request->validate([
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
]);
don't you need to pass duplicate column in ignore Rule To instruct the validator to ignore the website domain, except for it self ? for example like
Rule::unique('apps')->ignore($website->id)
please try this one . it helps to solve your problem
use exception and validator in top of the file
use Exception;
use Validator;
$rules = [
'subDomainName' => 'required|unique:sub_domain_name',
];
$validator = Validator::make($request->all(), $rules, $message);
if ($validator->fails()) {
throw new Exception(implode('\n', $validator->errors()->all()));
}
sub_domain_name : this is database column name
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']) ?>
In base PasswordResetRequestForm model:
public function rules()
{
return [
['email', 'exist',
'targetClass' => '\common\models\User',
'filter' => ['status' => User::STATUS_ACTIVE],
'message' => 'Such user is not registered. '.BaseHtml::a('Signup.',['site/signup'])
],
];
}
But link renders encoded. How to force it not to be encoded? Where should I do it, in ActiveForm, in field config, or in validation rule?
I don't know about the past, but now you can configure it in the fieldConfig:
$form = ActiveForm::begin([
'fieldConfig' => [
'errorOptions' => ['encode' => false],
],
]);
You can configure this on ActiveForm :
<?php $form = ActiveForm::begin([
'encodeErrorSummary' => false,
]); ?>
Read more : http://www.yiiframework.com/doc-2.0/yii-widgets-activeform.html#$encodeErrorSummary-detail