Yii2: How to validate input fields without using model in Yii2 Rest.

Created on 8 Jun 2018  路  7Comments  路  Source: yiisoft/yii2

let's say i have a controller called "trendController".
in index method, there is a logic which need to save some form data which will show some output to user after validation.

Now input data is something like
name - Should be text only,
amount - Number or decimal only,
email - A valid email,
phone - Only number, no country code..

Remember, there is no model play any role here. so how to validate these input in proper yii2 ways.

question

Most helpful comment

try it DynamicModel

All 7 comments

try it DynamicModel

It is called "Ad Hoc Validation" https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation

It allows you to validate any single value with any yii2 validator without any models.

If you want to validate more than one or two fields, DynamicModel is preferred approach, as it has simpler syntax than multiple Ad Hoc validators. https://www.yiiframework.com/doc/api/2.0/yii-base-dynamicmodel as rustamwin already suggested

Thanks @rustamwin @Deele
It's working exactly what I want but how to set custom errors.

Thank you for your question.
In order for this issue tracker to be effective, it should only contain bug reports and feature requests.

We advise you to use our community driven resources:

If you are confident that there is a bug in the framework, feel free to provide information on how to reproduce it. This issue will be closed for now.

_This is an automated comment, triggered by adding the label question._

In a controller file -

public function actionSearch(){
  $name = 123;  // string check      (Error  - your name is invalid)
  $email = 'error_gmail.c';   // wrong email check (Error  - your email is invalid) 
  $inputArray = array('name', 'email');

  $model = new DynamicModel(compact('name', 'email'));
  $model->addRule(['name', 'email'], 'string', ['max' => 50], ['message'=> '?? #1])
  ->addRule('email', 'email', ['message' => "Your email format is invalid. #2"]) 
  ->validate();

  if ($model->hasErrors()) {
       echo 'validation fails';
       print_r($model->getErrors());
  } else {
    echo 'validation pass';
    }
}

#1 I want to set four errors (2 input X 2 type of validation)
#2 worked for single attribute validation

So how to acheive this?

@rustamwin @Deele

Was this page helpful?
0 / 5 - 0 ratings