2

By the book, you suppose to manage post requests with core validators and rules that are described within a model. The problem comes up if you want to use a separate variable elsewhere.

First you get it from the request i.e.

$var = \Yii::$app->request->post('var');

Then you need to validate it before use. For example, it needs to be an email. Yii2 has a standard validator 'email', but how do I apply it separately?

I would assume something like this:

if( !\Yii::$app->coreValidator( $var, $rule ) )
    return $this->error();
Danil
  • 3,348
  • 2
  • 20
  • 16

2 Answers2

2

For Example,

$email = 'test@example.com';
$validator = new yii\validators\EmailValidator();

 if($validator->validate($email, $error)) {
  echo 'Email is valid.'; 
 } 
 else {
  echo $error;
 }

Validate Variable Without Model

You can use any validator or make your own validator by extending Validators Class.

Insane Skull
  • 9,220
  • 9
  • 44
  • 63
  • Yep, also just found it accidentally in official documentation: [Ad Hoc Validation](http://www.yiiframework.com/doc-2.0/guide-input-validation.html#ad-hoc-validation) – Danil Oct 31 '15 at 10:12
0

You can create simple validator

namespace app\components;
use yii\validators\Validator;

class CountryValidator extends Validator
{

    public function validateAttribute($model, $attribute)
    {
        if (!in_array($model->$attribute, ['USA', 'Web'])) {
            $this->addError($model, $attribute, 'The country must be either "USA" or "Web".');
        }
    }
}

This is a link of offical doucmentation Yii2

Vahe Galstyan
  • 1,681
  • 1
  • 12
  • 25