YII Ad hoc validation

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Ad hoc Validation

To validate values that are not bound to any model, we need to use ad hoc validation. Or if you want to validate values without models then use ad hoc validation.

To perform one type of validation, you may call yiivalidatorsvalidator() method of the desired validator.

Not all the valdiators support this type of validation.

For example, we are calling yiivalidatorsDateValidator()

  1. $date = '24th November 2016, Thursday';  

  2.     $validator = new yiivalidatorsDateValidator();  

  3.   

  4.     if ($validator->validate($date, $error)) {  

  5.         echo 'Date is valid.';  

  6.     } else {  

  7.         echo $error;  

  8.     }  

But to perform multiple validations, against several values you can use yiiaseDynamicModel which defines both attributes and rules.

For example, here we are calling DynamicModel to validate date and email.

  1. public function actionAdHocValidation() {   

  2.     $model = DynamicModel::validateData([   

  3.         'date' => '24th November 2016, Thursday',   

  4.          'email' => 'abc@gmail.com'   

  5.     ], [   

  6.         [['date', 'email'], 'string', 'max' => 40],   

  7.      ]);   

  8.       

  9.     if ($model->hasErrors()) {   

  10.         var_dump($model->errors);   

  11.     } else {   

  12.         echo "success";   

  13.     }   

  14.     }  

On the browser, pass the URL

http://localhost/ad_hoc/frontend/web/index.php?r=site/ad-hoc-validation

YII Ad hoc validation 1

Look at the above output, both date and email have been validated at the same time.