You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony十进制数范围(含99)验证的小数兼容问题

Solution for Symfony Decimal Range Validation (Including 99 as Exception)

First, let's break down the root issue: The in 8..39 syntax in Symfony's Expression Language checks if the value is part of an integer sequence from 8 to 39, not a continuous numerical range. That's why decimal values like 8.5 are failing—they aren't integers in that sequence, so the expression returns false.

Here's a simple, regex-free fix: Replace the range operator with explicit numerical comparisons using >= and <=, which properly evaluate the actual numerical value of your decimal field, regardless of whether it's stored as a string (per Doctrine's decimal mapping) or a float:

/**
 * @var decimal
 * @Assert\Expression(
 *     "this.getFu5Weight() >= 8 and this.getFu5Weight() <= 39 or this.getFu5Weight() == 99",
 *     message="3. Weight at assessment: this value has to be between 8 and 39, or 99 if unknown"
 * )
 */
private $fu5Weight;

Why this works:

  • Unlike in 8..39, the >=/<= operators check the numerical value, not just integer membership. This validates all valid decimal values in the 8–39 range (e.g., 8.00, 15.75, 39.00) without issue.
  • The check for == 99 will also work with decimal-formatted values like 99.00, since Symfony's Expression Language handles automatic conversion between string-based decimals and numeric values.

Quick additional notes:

  • Your form's invalid_message is still relevant—it catches non-numeric input (like text), which is separate from the range validation handled by the @Assert\Expression.
  • If you need to strictly enforce 99.00 (instead of accepting 99 as an integer), you can adjust the check to this.getFu5Weight() == 99.00 to match your Doctrine mapping's scale: 2 setting.

内容的提问来源于stack exchange,提问作者Baby Webmaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:25:28