Answer the question
In order to leave comments, you need to log in
[[+content_image]]
How to make a range validator for yii2?
how to make a rangle validator in yii2
like a rule that the field value must be at least 1 and not more than 100
[['score'],'in','max'=>100,'min'=>1],
well how did you try to take it from yii1 did not work?
Answer the question
In order to leave comments, you need to log in
To start reading off. docs : www.yiiframework.com/doc-2.0/guide-tutorial-core-v...
[ [ 'score' ], 'compare', 'compareValue' => 1, 'operator' => '>=' ],
[ [ 'score' ], 'compare', 'compareValue' => 100, 'operator' => '<=' ],
# или
[ [ 'score' ], 'in', 'range' => [ 1, ..., 100 ] ],
# или
[ [ 'score' ], function ( $attribute, $params ) {
if ( !( $this->$attribute >= 1 && $this->$attribute <= 100 ) ) {
# Ошибка!
}
} ],
[['score'], 'integer', 'min' => 1, 'max' => 100, 'message' => 'Invalid range'],
An example of an "in range" validator for dates:
public function rules()
{
return [
[['date'], 'required'],
[['date'], 'safe'],
[['date'],
'filter',
'filter' => function($value){
return \Yii::$app->formatter->asDate($value, 'yyyy-MM-dd');
}
],
[
['date'],
'date',
'format' => 'yyyy-MM-dd'
],
[
['date'],
'in',
'range' => function ($model, $attribute) {
$start = \Yii::$app->formatter->asTimestamp(!empty($model->oldAttributes[$attribute]) ?
$model->oldAttributes[$attribute] :
$this->$attribute);
$start += 24 * 60 * 60;
$stop = \Yii::$app->formatter->asTimestamp($model->relatedModel->end_date);
$dates = [];
while ($start <= $stop) {
$dates[] = \Yii::$app->formatter->asDate($start, 'MM/dd/yyyy');
$start += (24 * 60 * 60);
}
return $dates;
},
'on' => [
self::SCENARIO_DEFAULT,
],
'skipOnEmpty' => false,
'skipOnError' => false
],
];
}
<?php
$form = ActiveForm::begin();
$model->date = \Yii::$app->formatter->asDate($model->date, 'MM/dd/yyyy');
?>
<?= $form->field($model, 'date')
->label('Date')
->widget(DatePicker::className(), [
'dateFormat' => 'MM/dd/yyyy',
])
->textInput([
'class' => 'form-control',
]);
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question