我正在开发的应用程序接受来自非英语地区(主要是丹麦语)的用户的十进制数字。
验证数字的代码如下所示:
$fmt = new NumberFormatter($locale, NumberFormatter::DECIMAL);
$amount = $fmt->parse($input);
if ($amount === false) {
echo "There has been an error with the number {$input}";
}这很好用,因为它为字符串抛出错误,并接受小数。我对NumberFormatter的问题是,例如"12,34,,,5,34“被接受并格式化为12.34
现在,"12,34,,,5,34“不是十进制数,它应该被拒绝。我尝试将其与is_numeric()结合使用,但is_numeric()同时拒绝了"" 12,34,,,5,34“和12,34。
我的问题是,有没有办法让NumberFormatter拒绝"12,34,,,5,34“,因为这不是数字?
发布于 2020-05-07 21:47:44
NumberFormatter不用于输入验证。您可以尝试使用filter_var/filter_input方法:
<?php
setlocale(LC_ALL, 'de_DE');
$options = [
'options' => [
'decimal' => \localeconv()['decimal_point'],
],
];
$input = '10,0205,,04';
var_dump(
filter_var($input, FILTER_VALIDATE_FLOAT, $options)
);
# bool(false)
$input = '10,0205';
var_dump(
filter_var($input, FILTER_VALIDATE_FLOAT, $options)
);
# float(10.0205)希望我能帮上忙
/Flo
https://stackoverflow.com/questions/61658534
复制相似问题