[英]Performant way to validate numerics or range of numerics with RegexValidator in Django
我有一个具有CharField
字段的模型,该字段只能接受数字或一定范围的数字。 如果数字是十进制且小于1,则数字必须带有前导零;如果它们是整数,则除非尾随期间具有尾随零,否则它们不能具有尾随期间。 范围用连字符表示,并且不能包含任何空格。 我正在使用Django的RegexValidator
来验证字段。
注意:如果范围是相反的我不在乎(如6-3
, 10.3-0.13
)
这些是应该在验证器中传递的值的一些示例:
5
0.42
5.0
5-6
5-6.0
0.5-6.13
5.1-6.12
13.214-0.1813
这些对于验证器应该是无效的值:
5.
5.1.3
5.13.215
5-13.2-14
.13-1.31
5-6.
5 - 6
my_field = models.CharField(
...
validators=[
RegexValidator(
r'^[0-9]+([.]{1}[0-9]+){0,1}([-]{1}[0-9]+([.]{0,1}[0-9]+){0,1}){0,1}$',
message='Only numerics or range of numerics are allowed.'
)
]
)
如您所见,这是一个非常粗糙的regex模式,但我不确定该模式是否有效。 我不是正则表达式专家,所以如果有人提供更好的解决方案,我将不胜感激。
我将使用以下正则表达式模式:
^\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)?$
这说明:
\d+ match an initial whole number component
(?:\.\d+)? followed by an optional decimal component
(?:
- range separator
\d+ second whole number
(?:\.\d+)? with optional decimal component
)? the range being optional
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.