3

I have been working with Django and RegexValidator on a field where I would only like to save a valid US Zipcode in the format of DDDDD or DDDDD-DDDD.

I have set up my variable in the model as the following:

zip = models.CharField(
    max_length=10,
    null=True,
    blank=True,
    help_text=_("Zipcode"),
    validators=[RegexValidator(
        regex=r'^(^[0-9]{5}(?:-[0-9]{4})?$)?$)',
        message=_(u'Must be valid zipcode in formats 12345 or 12345-1234'),
    )],
)

At this point, I am trying to create a regex that will also save empty strings as well. I have tried to look at the following questions RegEx for 5 digit zip or empty Regex empty string or email and tried adding a "|" before, as well as an "?" at the end.

Any other suggestions or advice?

Community
  • 1
  • 1
RCN
  • 671
  • 1
  • 5
  • 17

1 Answers1

2

I believe you just want this as your regex: ^(^[0-9]{5}(?:-[0-9]{4})?$|^$)

It matches either an 5 digit string followed by an option dash and four digits or an empty string.

This was tested in the online regex tester

gymbrall
  • 2,063
  • 18
  • 21
  • when i enter '' I get ```Your pattern does not match the subject string.```but there might be something else in my code thats blocking this from saving. im going to revisit and try with this – RCN Jul 09 '15 at 20:53
  • ok, let us know how it goes. (also, just FYI, I believe the initial carat is unnecessary) – gymbrall Jul 11 '15 at 20:01