Skip to content

Commit a462a4e

Browse files
committed
fix: MoneyValidator allows negative
1 parent 51385a5 commit a462a4e

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

MoneyValidator.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,20 @@
1212

1313
class MoneyValidator extends Validator
1414
{
15+
public $pattern = '';
16+
17+
public $allowsNegative = false;
18+
1519
/**
1620
* 验证数字是两位小数、一位小数、整数
1721
* @param \yii\base\Model $model
1822
* @param string $attribute
1923
*/
2024
public function validateAttribute($model, $attribute)
2125
{
26+
$pattern = $this->allowsNegative ? '/^\-?\d+(\.\d{1,2})?$/i' : '/^\d+(\.\d{1,2})?$/';
2227
$value = $model->$attribute;
23-
if (!preg_match("/^\d+(\.\d{1,2})?$/", $value)) {
28+
if (!preg_match($this->pattern ?: $pattern, $value)) {
2429
$this->addError($model, $attribute, $this->message ?: '请输入正确的金额');
2530
}
2631
}

README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public function rules()
3838
{
3939
return [
4040
// ...
41-
['id_card', \yiier\validators\IdCardValidator::className()],
41+
['id_card', \yiier\validators\IdCardValidator::class],
4242
// code
4343
];
4444
}
@@ -51,7 +51,7 @@ public function rules()
5151
{
5252
return [
5353
// ...
54-
['product_ids', \yiier\validators\ArrayValidator::className()],
54+
['product_ids', \yiier\validators\ArrayValidator::class],
5555
// code
5656
];
5757
}
@@ -64,7 +64,7 @@ public function rules()
6464
{
6565
return [
6666
// ...
67-
['phone', \yiier\validators\PhoneValidator::className()],
67+
['phone', \yiier\validators\PhoneValidator::class],
6868
// code
6969
];
7070
}
@@ -78,7 +78,8 @@ public function rules()
7878
{
7979
return [
8080
// ...
81-
['amount', \yiier\validators\MoneyValidator::className()],
81+
['amount', \yiier\validators\MoneyValidator::class],
82+
['amount', \yiier\validators\MoneyValidator::class, 'allowsNegative' => true],
8283
// code
8384
];
8485
}

0 commit comments

Comments
 (0)