Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegexValidator for Zipcodes

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?

like image 209
RCN Avatar asked Jul 29 '26 16:07

RCN


1 Answers

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

like image 183
gymbrall Avatar answered Aug 01 '26 08:08

gymbrall