在 symfony 2 中验证小数 [英] Validating decimals in symfony 2

查看:19
本文介绍了在 symfony 2 中验证小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Doctrine 将 symfony2 实体映射到表.属性之一是:

I have symfony2 entity mapped to a table using Doctrine. One of the properties is:

/**
 * @var decimal $price
 *
 * @ORM\Column(name="price", type="decimal", nullable=false)
 */
private $price;

什么Assert 会满足我的要求,$price 应该是一个有效的小数?

What Assert would satisfy my requirement that $price should be a valid decimal?

如果我保持原样,那么将字符串 foo 作为十进制值传递将导致验证错误,而传递字符串 NaN 将通过验证,因为字符串 >NaN 被映射为 float(NaN) 因此被视为有效的十进制值.

If I stay things as-is then passing string foo as a decimal value will lead to validation error, while passing string NaN passes validation, because the string NaN is mapped as float(NaN) thus treated as a valid decimal value.

有什么解决方法吗?

Symfony 开发团队保证这不是问题:https://github.com/symfony/symfony/issues/3161

Symfony dev team assures it is not an issue: https://github.com/symfony/symfony/issues/3161

好吧,如果不是 - 那么可能有一个解决方案来验证它.有什么想法吗?

Well, if it is not - then there is probably a solution to validate it. Any ideas?

推荐答案

从 Symfony 文档来看,没有内置的小数验证器.您可以使用回调验证器,或者更好的是您可以创建自己的自定义验证器,如本文此处所述.

From looking at the Symfony documentation, there isn't a built in validator for decimals. You could use a callback validator, or better still you could create your own custom validator like this article describes here.

至于实际验证,我会使用 is_numericis_float 的组合来检查.有使用正则表达式的方法,但在我看来,如果值满足 is_numericis_float 检查,那么您可以安全地假设它是有效的小数(或整数).

As for the actual validation, I'd use a combination of is_numeric and is_float to check. There are methods using regex, but in my opinion if the value satisfies either the is_numeric or is_float check then you can safely assume it is a valid decimal (or a whole number).

也许最好的解决方案是将十进制验证为字符串.像……

Maybe the best solution would be to validate the decimal as a string. Something like...

$stringDecimal = strval($decimalValue);
return (preg_match(/[0-9]+(\.[0-9][0-9]?)?/, $stringDecimal) !== 0);

虽然这并不完美(您可以轻松地通过1.15adowadjaow"并进行验证),但它是您所追求的基础.将上述正则表达式与搜索除 0-9、句号或逗号以外的任何内容的内容相结合(取决于您是否想要满足欧洲十进制格式).

Whilst this isn't perfect (you could easily pass '1.15adowadjaow' and it would validate), it serves the basis of what you're after. Combining the above regex with something that searches for anything other than 0-9, fullstop or comma (depending if you want to cater for European decimal formatting).

这篇关于在 symfony 2 中验证小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆