PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 19, 2022

[FIXED] Validation IRAN Code Meli in Ajax ActiveForm Yii2

 March 19, 2022     active-form, yii, yii2     No comments   

Issue

how to Validation IRAN Code Meli in Ajax ActiveForm Yii2

Correct:

2595722751

not Correct:

2595722752

Solution

Step1: in view

<?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?>

Step2: function in model

public function checkCodeMeli()
    {
        $code_melli = $this->code_meli;

        if (!preg_match('/^[0-9]{10}$/', $code_melli)) {
            $this->addError('code_meli', 'کد ملی باید 10 رقم باشد');
        }

        for ($i = 0; $i < 10; $i++) {
            if (preg_match('/^' . $i . '{10}$/', $code_melli)) {
                $this->addError('code_meli', 'کد ملی صحیح وارد نشده است');
            }
        }

        for ($i = 0, $sum = 0; $i < 9; $i++) {
            $sum += ((10 - $i) * intval(substr($code_melli, $i, 1)));
        }

        $ret = $sum % 11;
        $parity = intval(substr($code_melli, 9, 1));
        if (($ret < 2 && $ret == $parity) || ($ret >= 2 && $ret == 11 - $parity)) {
            return true;
        }
        else {
            $this->addError('code_meli', 'کد ملی صحیح وارد نشده است');
        }
    }

Step3: rule in Model

['code_meli', 'checkCodeMeli'],

Step4: in controller

$model = new Model();

if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
   Yii::$app->response->format = Response::FORMAT_JSON;
   return ActiveForm::validate($model);
}


Answered By - user3770797
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing