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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With