[英]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.