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?