简体   繁体   English

在Django中使用RegexValidator验证数字或数字范围的有效方式

[英]Performant way to validate numerics or range of numerics with RegexValidator in Django

The problem 问题

I have a model that has a CharField field, where the field can only accept numerics or a range of numerics. 我有一个具有CharField字段的模型,该字段只能接受数字或一定范围的数字。 The numerics must either have a leading zero if they are decimal and are <1, and if they are a whole number, they cannot have a trailing period unless the trailing period has a trailing zero. 如果数字是十进制且小于1,则数字必须带有前导零;如果它们是整数,则除非尾随期间具有尾随零,否则它们不能具有尾随期间。 The ranges are delineated using a hyphen and must not contain any spaces. 范围用连字符表示,并且不能包含任何空格。 I'm using Django's RegexValidator to validate the field. 我正在使用Django的RegexValidator来验证字段。

Note: I don't care if the ranges are reversed (eg 6-3 , 10.3-0.13 ) 注意:如果范围是相反的我不在乎(如6-310.3-0.13

These are some examples of values that should pass in the validator: 这些是应该在验证器中传递的值的一些示例:

  • 5
  • 0.42
  • 5.0
  • 5-6
  • 5-6.0
  • 0.5-6.13
  • 5.1-6.12
  • 13.214-0.1813

These should be invalid values for the validator: 这些对于验证器应该是无效的值:

  • 5.
  • 5.1.3
  • 5.13.215
  • 5-13.2-14
  • .13-1.31
  • 5-6.
  • 5 - 6

My current solution 我目前的解决方案

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.'
        )
    ]
)

What I need help at 我需要什么帮助

As you can see, this is a pretty gnarly regex pattern, and I'm not so sure if this pattern is performant. 如您所见,这是一个非常粗糙的regex模式,但我不确定该模式是否有效。 I'm not a regex guru so I'd appreciate if someone offers a better solution. 我不是正则表达式专家,所以如果有人提供更好的解决方案,我将不胜感激。

I would use this regex pattern: 我将使用以下正则表达式模式:

^\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)?$

This says to: 这说明:

\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

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM