Behzad Hassani
Behzad Hassani

Reputation: 2139

Dynamic Regular Expression Yii2

I want to use dynamic regular expression for model validation in yii2 for example we use regular expresstion as below:

[['password'], 'match', 'pattern' => '/^[A-Za-z0-9_@%&*]{6,32}$/'],

now I want to load value of pattern from database. Is it possible ? If it is please explain your soultion. Thank to all.

Upvotes: 1

Views: 1283

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133360

Try assigning the regexp to a var

$myRegExp = " '/^[A-Za-z0-9_@%&*]{6,32}$/'";

then

[['password'], 'match', 'pattern' => $myRegExp],

You can create a proper class for store and retrieve you regexp string form database. eg: MyDBRegExpModel the with a function getMyRegExp($param) retrieve the value you need.. and last add your db access before the return and assignment is r(model) rules

In your Model

class MyModel extends \yii\db\ActiveRecord
{
   /**
   * @inheritdoc
   */
   public static function tableName()
   {
      return ......;
   }

   /**
   * @inheritdoc
   */     
   public function rules()
   {
       $myModel = MyDBRegExpModel::getMyRegExp($param);

       return [
         ......
         [['password'], 'match', 'pattern' => $myModel->myRegExp],
         ......
        ];
    }

Upvotes: 1

Related Questions