Last active
March 26, 2018 07:44
-
-
Save lastday154/9a0bf4143bfc73dadad703bb3df92962 to your computer and use it in GitHub Desktop.
Yii Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Validator extends CFormModel | |
| { | |
| public $id; | |
| public function rules() | |
| { | |
| return [ | |
| [['id'], 'required'], | |
| ['id', 'length', 'max' => 50], | |
| ['price', 'validatePrice'], | |
| ]; | |
| } | |
| public function validatePrice($attribute, $params) | |
| { | |
| $price = $this->$attribute; | |
| $allowEmpty = isset($params['allowEmpty']) ? $params['allowEmpty'] : true; | |
| if ($allowEmpty && !$price) return; | |
| $iso = new FbIsoFormat(); | |
| $result = $iso->validatePrice($price); | |
| if (!$result) { | |
| $this->addError($attribute, 'Amount is not match to ISO 4217 standard. The format should be "number plus unit (ISO 4217)"'); | |
| } | |
| } | |
| public function getErrorList($fields = []) { | |
| $errors = $this->getErrors(); | |
| $data = []; | |
| foreach ($fields as $field) { | |
| if (!isset($this->$field)) continue; | |
| $fieldData = [ | |
| 'is_hidden' => 0, | |
| 'readOnly' => 1, | |
| 'key' => $field, | |
| 'value' => $this->$field, | |
| 'label' => $field, | |
| 'is_valid' => 1, | |
| 'is_required' => 0, | |
| 'type' => 'string' | |
| ]; | |
| if (array_key_exists($field, $errors)) { | |
| $fieldData['is_valid'] = 0; | |
| $fieldData['error_msg'] = implode(", ", $errors[$field]); | |
| } | |
| $data[$field] = $fieldData; | |
| } | |
| return $data; | |
| } | |
| } | |
| $validator = new Validator(); | |
| $product = ['id' => '123', 'title' => 'Hello Steve, you are awesome' ]; | |
| $validator->attributes = $product; | |
| $validator->validate(); | |
| return $validator->getErrors(); | |
| return $validator->getErrorList(array_keys($product)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment