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
== 99will 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_messageis 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.00to match your Doctrine mapping'sscale: 2setting.
内容的提问来源于stack exchange,提问作者Baby Webmaster
相关产品推荐
相关产品推荐

