简体   繁体   中英

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. 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. The ranges are delineated using a hyphen and must not contain any spaces. I'm using Django's RegexValidator to validate the field.

Note: I don't care if the ranges are reversed (eg 6-3 , 10.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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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