使用 Respect\Validation 的 Decimal 校验器精确验证小数位数:用法、模板与源码原理

原创2026-10-05 11:28:131,973 阅读
文章标签:后端开发工具

使用 Respect\Validation 的 Decimal 校验器精确验证小数位数:用法、模板与源码原理

Decimal 是 Respect\Validation 校验器中用于精确验证数值小数位数的专用规则:通过 v::decimal(int $decimals) 指定期望的小数位,即可判定输入(字符串或数值)是否恰好匹配该精度,例如校验金额 27990.50 是否为 2 位小数。本文以 docs/validators/Decimal.md 为主体,结合 Decimal.php 源码 及其单元/特性测试,完整讲解其调用方式、字符串与浮点数的行为差异、错误消息模板定制,以及它在链式复合 API 中的实际用法;读完本文你可以在项目中准确控制小数精度校验,并理解其底层判定原理与已知边界。

核心签名与基本用法

Decimal 校验器的唯一构造参数是小数位数:

Decimal(int $decimals)

其中 $decimals 是期望的十进制小数位数(int 类型),如 0 表示整数精度、2 表示两位小数。官方文档给出的三个典型示例:

v::decimal(2)->assert('27990.50');
// Validation passes successfully

v::decimal(1)->assert('27990.50');
// → "27990.50" must have 1 decimal places

v::decimal(1)->assert(1.5);
// Validation passes successfully

可以看到:字符串 '27990.50' 恰好是两位小数,所以 decimal(2) 通过,而 decimal(1) 会因实际精度不匹配而抛出异常。数值 1.5 本身是一位小数,decimal(1) 校验通过。失败时 assert() 抛出 Respect\Validation\Exceptions\ValidationException,默认消息模板即上文的“must have ... decimal places”句式。

字符串与数值输入:两种判定路径

从 src/Validators/Decimal.php 的源码结构可以清晰看到,判定过程对字符串输入与数值输入走了两条不同的路径:

  • evaluate() 先调用 is_numeric($input) 做门槛检查:非数值输入(如布尔值、数组、对象、NAN)直接判定失败;
  • isValidDecimal() 的判据是 toFormattedString($input) === toRawString($input),即“按期望小数位格式化后的字符串”必须与“原始字符串表示”完全相等;
  • toRawString():字符串输入原样返回,数值输入则用 var_export($input, true) 转成其字符串表示(例如 1.5、1.0);
  • toFormattedString():用 number_format((float) $input, $this->decimals, '.', '') 格式化为固定小数位、无千分位分隔符的字符串;仅当输入是字符串时才直接返回该格式化结果,若输入是数值,还要再经 preg_replace('/^(\d+\.\d)0*$/', '$1', $formatted) 去掉尾部多余的零。

字符串 '27990.50' 配合 decimal(2) 时,格式化结果为 '27990.50',与原始字符串相等,校验通过;配合 decimal(1) 时格式化结果为 '27990.5',与原始字符串 '27990.50' 不等,校验失败。这解释了文档示例的全部行为。

已知限制:浮点数的尾部零无法判定

官方文档专门标注了 Decimal 的一个已知局限(Known limitations):当输入是浮点类型时,无法判定其数值末尾是否存在多余的零,因此下面的校验会意外通过:

v::decimal(1)->assert(1.50);
// Validation passes successfully

其根源正是上一节提到的源码分支:浮点输入在格式化后会被 preg_replace('/^(\d+\.\d)0*$/', '$1', $formatted) 剥离尾部零,1.50 被格式化为 '1.5',而 var_export 得到的原始表示同样是 '1.5',二者相等,于是 decimal(1) 判定通过。也就是说,对浮点输入只能判断“至少需要的小数位数”,无法严格区分 1.5 与 1.50;若业务上必须严格区分(例如金额单据校验),应使用字符串形式传入数值。

这一行为也被 tests/unit/Validators/DecimalTest.php 的用例固化:[new Decimal(1), 1.50]、[new Decimal(2), 1.000]、[new Decimal(1), 10.0]、[new Decimal(1), 10.50]、[new Decimal(2), 10.50] 等浮点输入均为“有效输入”,而字符串 [new Decimal(1), '1.50']、[new Decimal(1), '27990.50'] 则被列为“无效输入”。

边界输入:非数值与非有限值

单元测试的无效输入集进一步明确了边界行为(tests/unit/Validators/DecimalTest.php):

[new Decimal(0), 2.0],        // 浮点 2.0 带多余零 → 无效
[new Decimal(0), acos(1.01)], // NAN
[new Decimal(0), sqrt(-1)],   // NAN
[new Decimal(0), NAN],
[new Decimal(0), -NAN],
[new Decimal(0), false],
[new Decimal(0), true],
[new Decimal(0), []],
[new Decimal(0), new stdClass()],
  • 浮点 2.0 在 decimal(0)(期望 0 位小数)下无效,因为它被归一化后表示的是整数而非“0 位小数格式”;
  • NAN(含 acos(1.01)、sqrt(-1) 等产生 NaN 的运算结果)无法通过 is_numeric() 门槛检查,直接失败;
  • 布尔值、数组、对象等非数值类型同样在 is_numeric() 处被拦截。

对应的有效输入集包括 [new Decimal(0), 1]、[new Decimal(1), 1.0]、[new Decimal(2), 1.00]、[new Decimal(3), 1.000]、[new Decimal(2), '27990.50']、[new Decimal(1), 1.1]、[new Decimal(1), '1.3']、[new Decimal(3), '1.000']、[new Decimal(3), 123456789.001] 等,可作为你编写校验规则时的参考基准。

错误消息与模板定制

Decimal 通过 PHP 8 原生属性 #[Template(...)] 声明了标准模板(即 Decimal::TEMPLATE_STANDARD),默认与反转(inverted)两种模式如下:

Mode Template
default {{subject}} must have {{decimals}} decimal places
inverted {{subject}} must not have {{decimals}} decimal places
Placeholder Description
decimals 校验器构造参数中指定的期望小数位数(即 $decimals 的值)
subject 被校验的原始输入,或(若指定了)自定义校验器名称

特性测试 tests/feature/Validators/DecimalTest.php 验证了四种典型消息输出:

v::decimal(3)->assert(0.1234);
// "0.1234 must have 3 decimal places"

v::decimal(2)->assert(0.123);
// 完整消息: "- 0.123 must have 2 decimal places"

v::not(v::decimal(5))->assert(0.12345);
// "0.12345 must not have 5 decimal places"

v::not(v::decimal(2))->assert(0.34);
// 完整消息: "- 0.34 must not have 2 decimal places"

其中 v::not(...) 使校验逻辑反转,对应 inverted 模板“must not have ... decimal places”。subject 占位符允许通过命名机制覆盖:使用自定义校验器名称时,错误消息中的 {{subject}} 会显示为自定义名称而非原始输入,便于在复合校验中精确定位出错字段。

在链式与复合 API 中使用

Decimal 不仅在 Numbers 分类 中作为一个独立校验器存在,还被深度集成进 Respect\Validation 的混入(Mixin)体系,在 src/Mixins 下生成了多个链式入口:

因此可以很方便地组合出完整规则,例如校验“数组每个元素都是保留两位小数的非负数值”:

v::each(v::decimal(2))->assert(['12.50', '0.99']);

此外,从源码看 Decimal 类被标注为 #[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)],这意味着它还可作为 PHP 8 原生属性直接声明在类属性上,用于属性级别的声明式校验,且允许重复标注。

相关校验器

Decimal 属于“Numbers(数字)”类别(见 docs/validators.md),官方文档列出的相关校验器包括:

在实际业务中,常与 NumericVal(判断输入是否为数值)、FloatVal(浮点数值)或 Number(合法数字)搭配使用:先确认输入是数值,再通过 Decimal 精确约束小数位数。

版本变更记录

官方文档记录的 Decimal 变更历史如下:

Version Description
3.0.0 Templates changed(模板体系改为 TEMPLATE_STANDARD)
2.2.4 Float values with trailing zeroes are now valid(带尾部零的浮点值现在视为有效)
2.0.0 Created(校验器创建)

其中 2.2.4 的变更正是本文“已知限制”一节所述行为被引入的时间点:从该版本起,浮点输入在比较前会剥离尾部零,因此 v::decimal(1)->assert(1.50) 被判定为通过;3.0.0 则把错误消息重构为当前的模板占位符体系({{subject}}、{{decimals}}),并支持 inverted 反转模板。

小结

Decimal 是 Respect\Validation 中针对小数精度的精确校验器:以整数参数声明期望小数位,对字符串输入严格匹配、对浮点输入按“剥离尾部零”后的归一化表示判定(这也是其唯一已知局限);失败消息可通过 TEMPLATE_STANDARD 的默认/反转模板与 {{subject}}、{{decimals}} 占位符定制;在混入体系中还提供了 decimal()、allDecimal()、keyDecimal() 以及 not/nullOr/undefOr 等变体便于链式组合。需要进一步了解安装与整体使用方式时,可查阅 getting-started 与 validators 总览。

登录后查看全文
Validation