0

I have a dropdownlist with other option have text field. now i want to validate both dropdownlist and text-field. Validation apply according to the selection i.e. dropdown or text-field. How can i apply this.

Year come from dopedown. Here i have id

['year', 'integer'],

Or come from text field . Here i have year

['year', 'integer', 'min' => 1900, 'max' => date('Y')],
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Bell Carson
  • 127
  • 9
  • You should always validate in the same way - in dropdown you can send any value you want, just like in text field. – Yupik Aug 23 '17 at 06:38

2 Answers2

0

For this purpose you can use sceanrio in yii2 validation. For example:

class User extends ActiveRecor{
const SCENARIO_INPUT = 'text_inpu';
const SCENARIO_DROPDOWN = 'dropdown_list';
public function scenarios(){
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_INPUT];
    $scenarios[self::SCENARIO_DROPDOWN];
    return $scenarios;}

public function rules(){
    return [[['year'], 'integer', 'on' => self::SCENARIO_DROPDOWN],
           [['year'], 'integer', 'min' => 1900, 'max' => date('Y') 'on' => self::SCENARIO_DROPDOWN]];}}
vityapro
  • 178
  • 1
  • 13
0

In your case you need to write a custom validation function in your model and use a another variable for capture year from text field. Your model code should like :

use yii\base\Model;

class YourModel extends Model
{
  // use variable for capture year in text field
  public $year_as_other;

  public function rules()
  {
    return [
        // an inline validator defined as the model method validateYear()
        ['year', 'validateYear'],
        ['year_as_other' , 'safe'],
    ];
 }

 public function validateYear($attribute)
 {
   if($this->year ==  'other' && ($this->year_as_other < 1900 || $this->year_as_other > date('Y')))
   {
     $this->addError($this->year_as_other , 'Invalid Year'); // your error message
   }
   elseif($this->year < 1900 || $this->year > date('Y'))
   {
      $this->addError($this->year , 'Invalid year');// your error message
   }
 }
}