DecimalNumber.php 748 B

12345678910111213141516171819202122232425262728
  1. <?php
  2. namespace App\Rules;
  3. use Illuminate\Contracts\Validation\Rule;
  4. class DecimalNumber implements Rule
  5. {
  6. public function __construct(private int $integerDigits = 14, private int $decimalPlaces = 4)
  7. {
  8. }
  9. public function passes($attribute, $value): bool
  10. {
  11. if (!is_string($value) && !is_int($value) && !is_float($value)) {
  12. return false;
  13. }
  14. return preg_match(
  15. '/^\d{1,' . $this->integerDigits . '}(?:\.\d{1,' . $this->decimalPlaces . '})?$/D',
  16. (string) $value
  17. ) === 1;
  18. }
  19. public function message(): string
  20. {
  21. return ':attribute 格式错误,最多 ' . $this->integerDigits . ' 位整数和 ' . $this->decimalPlaces . ' 位小数';
  22. }
  23. }