Tutorials
Last updated on:
January 27, 2025

How to validate ZIP codes in your Webflow forms

BRIX Templates Logo
Author
BRIX Templates
How to validate ZIP codes in your Webflow forms
Article changelog

Jan 27, 2025 - Initial version of the article published

Table of contents

In the world of form validation, ZIP and postal codes present a unique challenge. While Webflow offers robust form-building capabilities, it doesn't include built-in ZIP code validation—leaving many businesses struggling to ensure their forms collect valid postal codes. This guide will walk you through implementing a powerful, flexible ZIP code validation solution that works seamlessly with your Webflow forms.

Why proper ZIP code validation matters for your Webflow forms

It's great to have ZIP code validation for cases like:

Geographic service boundaries: If you only provide services in specific regions, ZIP code validation ensures users from outside your service area know immediately if you can't serve their location.

Lead qualification: For businesses that only operate in certain areas, validating ZIP codes helps qualify leads automatically, ensuring your sales team only receives relevant inquiries.

Form accuracy: By catching invalid postal codes early, you improve data quality and reduce the time spent cleaning up your database.

How to create a zip code postcode validator

Understanding our free Webflow ZIP code validator's capabilities

Our validator script offers 4 powerful validation methods that you can mix and match according to your needs:

  1. Country shortcuts (fastest implementation): The easiest way to validate postal codes—simply specify countries like "us" or "canada" and the validator will automatically check against all valid formats for that country. Built-in support for US, Canadian, UK, and Australian postal codes means you don't need to know the specific formats, just type the country and you are covered.
  2. Numeric ranges: Perfect for businesses serving specific geographic areas. Simply define a range of ZIP codes, and the validator will ensure submissions only come from within your service area.
  3. Exact matching: Ideal when you need to restrict submissions to very specific postal codes. This is particularly useful for single-location businesses or when managing precise delivery zones.
  4. Pattern matching: Enables custom validation formats using a simple placeholder system. This is especially valuable when standard country formats don't meet your specific needs.

How to create a ZIP/post code validator in Webflow

Let's walk through the implementation process step by step.

Step 1: Add the validator script to your site

  1. Navigate to your Webflow project settings
  2. Access the Custom Code section
  3. Locate the Footer code field
  4. Paste the following code:
<script>
/**
 * Zip/Postal Code Validator for Webflow Forms by BRIX Templates
 * (Support zip ranges, exact zip codes, patterns, and country regex shortcuts)
 *
 * This script validates user input against:
 *  1. Numeric Ranges: "35001-36999"
 *  2. Exact Codes: "31905"
 *  3. Pattern Placeholders: 
 *     - (0) => \d   [0-9]
 *     - (a) => [a-z]
 *     - (A) => [A-Z]
 *  4. Country Shortcuts: "us", "canada", "uk", "australia"
 *     - us => 5-digit or ZIP+4 (e.g. 12345 or 12345-6789)
 *     - canada => e.g. K1A 0B1 (uses official Canadian postal code format)
 *     - uk => standard UK postcodes (quite a complex pattern!)
 *     - australia => 4-digit numeric postcodes (e.g. 3000)
 *
 * Example usage in Webflow:
 *   1) On a text input field, add:
 *      brixtemplates-zipcode-validator-target="zip"
 *      brixtemplates-zipcode-validator-list="35001-36999, 31905, 100(0)(0), canada"
 *
 *   2) On an error message div, add:
 *      brixtemplates-zipcode-validator-error="zip"
 *
 *   3) On a submit button (optional):
 *      brixtemplates-zipcode-validator-submit="zip"
 *
 * If the user’s entry doesn't match ANY item in the list, the form is invalid.
 * The error message will display, and the submit button is disabled (if present).
 *
 * @version 1.0.0
 * Author: BRIX Templates
 */

(function() {
  'use strict';

  // Debounce function
  function debounce(fn, delay) {
    var timeout;
    return function() {
      var args = arguments;
      clearTimeout(timeout);
      timeout = setTimeout(function() {
        fn.apply(null, args);
      }, delay);
    };
  }

  // Known Country Regex Patterns (no ^ or $ here, they are added later)
  var countryRegexMap = {
    us: '[0-9]{5}(?:-[0-9]{4})?',
    canada: '[ABCEGHJ-NPRSTVXY]\\d[ABCEGHJ-NPRSTV-Z](?:\\s?\\d[ABCEGHJ-NPRSTV-Z]\\d)?',
    uk:
      '([Gg][Ii][Rr]\\s?0[Aa]{2})|' +
      '((([A-Za-z][0-9]{1,2})|' +
      '(([A-Za-z][A-HK-Ya-hk-y][0-9]{1,2})|' +
      '(([A-Za-z][0-9][A-Za-z])|' +
      '([A-Za-z][A-HK-Ya-hk-y][0-9]?[A-Za-z]))))' +
      '(\\s?[0-9][A-Za-z]{2}))',
    australia: '[0-9]{4}'
  };

  // Initialize once the DOM is loaded
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initBrixValidator);
  } else {
    initBrixValidator();
  }

  function initBrixValidator() {
    var fields = document.querySelectorAll('[brixtemplates-zipcode-validator-target]');
    if (!fields.length) return;

    fields.forEach(function(field) {
      var targetKey     = field.getAttribute('brixtemplates-zipcode-validator-target') || '';
      var errorElement  = document.querySelector('[brixtemplates-zipcode-validator-error="' + targetKey + '"]');
      var form          = field.closest('form');
      var submitButton  = form ? form.querySelector('[brixtemplates-zipcode-validator-submit="' + targetKey + '"]') : null;
      var listAttribute = field.getAttribute('brixtemplates-zipcode-validator-list') || '';

      // One single console.log as requested:
      console.log(
        'The BRIX Templates ZIP Form Validator for Webflow script has detected 1 validator with the validation "' +
        listAttribute +
        '"'
      );

      if (errorElement) {
        errorElement.style.display = 'none';
      }

      // Split the list items
      var rawItems = listAttribute
        .split(',')
        .map(function(i) { return i.trim(); })
        .filter(Boolean);

      // Parse each item
      var parsedEntries = rawItems.map(function(item) {
        var rangeMatch = item.match(/^(\d+)-(\d+)$/);
        if (rangeMatch) {
          var startNum = parseInt(rangeMatch[1], 10);
          var endNum   = parseInt(rangeMatch[2], 10);
          return {
            type: 'range',
            start: Math.min(startNum, endNum),
            end: Math.max(startNum, endNum)
          };
        }

        var lowerItem = item.toLowerCase();
        if (countryRegexMap[lowerItem]) {
          return {
            type: 'pattern',
            regex: new RegExp('^' + countryRegexMap[lowerItem] + '$', 'i')
          };
        }

        if (item.indexOf('(') !== -1) {
          var patternStr = item.replace(/\(([^)]+)\)/g, function(_, inside) {
            var expanded = inside.split('').map(function(char) {
              switch (char) {
                case '0': return '\\d';
                case 'a': return '[a-z]';
                case 'A': return '[A-Z]';
                default:  return char;
              }
            }).join('');
            return expanded;
          });
          return {
            type: 'pattern',
            regex: new RegExp('^' + patternStr + '$')
          };
        }

        return {
          type: 'exact',
          value: item
        };
      });

      // Validate
      function validateField() {
        var value = field.value.trim();
        if (!parsedEntries.length) return true;
        var isValid = parsedEntries.some(function(entry) {
          switch (entry.type) {
            case 'range':
              var numVal = parseInt(value, 10);
              if (isNaN(numVal)) return false;
              return (numVal >= entry.start && numVal <= entry.end);
            case 'exact':
              return (value === entry.value);
            case 'pattern':
              return entry.regex.test(value);
            default:
              return false;
          }
        });

        if (errorElement) {
          errorElement.style.display = isValid ? 'none' : 'block';
        }
        if (submitButton) {
          submitButton.style.opacity       = isValid ? '1' : '0.5';
          submitButton.style.pointerEvents = isValid ? 'auto' : 'none';
        }
        return isValid;
      }

      // Debounced validation
      var debouncedValidate = debounce(validateField, 400);

      // Events
      field.addEventListener('blur', validateField);
      field.addEventListener('input', debouncedValidate);
      if (form) {
        form.addEventListener('submit', function(evt) {
          if (!validateField()) {
            evt.preventDefault();
            field.focus();
          }
        });
      }
    });
  }
})();
</script>

This will add the ZIP postal code validator site-wide.

Add Webflow zip code validator script

If you only need validation on specific pages, you can instead add the code to individual pages through the Page Settings > Custom Code > Before </body> tag section of those specific pages.

Step 2: Configure your form field for validation

Now we need to tell our validator which form field to monitor. Here's how:

  1. Select your form's ZIP code input field in the Webflow Designer
  2. Click the gear icon to open Element Settings
  3. Scroll down to find the "Custom Attributes" section
  4. Add your first attribute:
    • In the "Name" field, enter: brixtemplates-zipcode-validator-target
    • In the "Value" field, enter: zip
  5. Add your second attribute:
    • In the "Name" field, enter: brixtemplates-zipcode-validator-list
    • In the "Value" field, you'll add your validation rules (more on that below!)
Setup zip code validation rules on Webflow form field

For the validation rules, you can use any of the formats we cover below in the How to configure validation rules section. For example, if you want to accept any valid US ZIP code, you'd enter us as the value. We'll explore many more options in the validation rules section below.

Step 3: Set up the error message display

The validator needs a way to show users when they've entered an invalid ZIP code. Here's how to set this up:

  1. Add a new Div block directly below your ZIP code field, or above your submit button
  2. Style this Div to match your form's design (this will be your error message)
  3. Add some text like "Please enter a valid ZIP code", "We only offer services in the [X] area", or anything that you prefer
  4. In the Div's Element Settings (gear icon), find "Custom Attributes"
  5. Add this attribute:
    • Name: brixtemplates-zipcode-validator-error
    • Value: zip
Customize error message for zip postal code validation on Webflow

Important: In the Div's Style panel, set the Display to "None", so this error message is hidden by default.

Enable error message for zip post code validator in Webflow site

This error message will automatically appear when users enter invalid codes and hide when they correct them. The display toggling is handled automatically by the validator script.

Step 4: Connect your submit button

Finally, we'll connect the submit button to prevent form submission when ZIP codes are invalid:

  1. Select your form's submit button in the Webflow Designer
  2. Click the gear icon to open Element Settings
  3. Find the "Custom Attributes" section
  4. Add this attribute:
    • Name: brixtemplates-zipcode-validator-submit
    • Value: zip
Setup zip code validation rules on Webflow form field

This connection ensures users can't submit the form until they enter a valid ZIP code. The button will automatically disable itself when the ZIP code is invalid and re-enable when a valid code is entered.

How to configure different ZIP validation rules for different business needs on your Webflow form

The validator's flexibility comes from its brixtemplates-zipcode-validator-list attribute. Here's how to configure it for common scenarios:

Accepting country-wide ZIP codes

For country-specific validation, use these shortcuts:

  • us: Accepts standard US ZIP codes (12345 or 12345-6789)
  • canada: Validates Canadian postal codes (e.g., K1A 0B1)
  • uk: Supports all valid UK postcode formats
  • australia: Accepts 4-digit Australian postcodes

Example:

brixtemplates-zipcode-validator-list="us"

Need to validate postal codes for other countries? Our Webflow team can help you customize the script to support additional country formats.

Accepting ZIP code number ranges

If your business only serves specific geographic areas, you can use numeric ranges to restrict submissions to those regions. For example, if you only provide services in the Los Angeles area, you might use:

brixtemplates-zipcode-validator-list="90001-90999"

This accepts any number between 90001 and 90999 (inclusive), which covers the Los Angeles County ZIP codes. This is particularly useful for:

  • Local service businesses
  • Regional shipping restrictions
  • State-specific programs

Want to restrict your Webflow form submissions to specific state/states (i.e. California or New York)? Below we compiled a list of all the ZIP code ranges for every US state. Simply copy the range you need and add it to your validation list attribute. Feel free to edit it as needed in case you need to have any specific limitations for certain ZIP codes.

Alabama: 31905,35001-36999
Alaska: 99501-99950
Arizona: 85001-86599
Arkansas: 71601-72999,75502
California: 90001-96199
Colorado: 80001-81699
Connecticut: 06001-06999
Delaware: 19701-19999
District of Columbia: 20001-20599,56901-56999
Florida: 32001-34999
Georgia: 30001-31999,39801-39899,39901
Hawaii: 96701-96899
Idaho: 83201-83899
Illinois: 60001-62999
Indiana: 46001-47999
Iowa: 50001-52899
Kansas: 66001-67999
Kentucky: 40001-42799
Louisiana: 70001-71499
Maine: 03901-04999
Maryland: 20601-21999
Massachusetts: 01001-02799,05501-05544
Michigan: 48001-49999
Minnesota: 55001-56799
Mississippi: 38601-39799
Missouri: 63001-65899
Montana: 59001-59999
Nebraska: 68001-69399
Nevada: 88901-89999
New Hampshire: 03001-03899
New Jersey: 07001-08999
New Mexico: 87001-88499
New York: 00501,00544,06390,10001-14999
North Carolina: 27001-28999
North Dakota: 58001-58899
Ohio: 43001-45999
Oklahoma: 73001-74999
Oregon: 97001-97999
Pennsylvania: 15001-19699
Rhode Island: 02801-02999
South Carolina: 29001-29999
South Dakota: 57001-57799
Tennessee: 37001-38599
Texas: 73301,73344,75001-79999,88501-88599
Utah: 84001-84799
Vermont: 05001-05999
Virginia: 20101-20199,22001-24699
Washington: 98001-99499
West Virginia: 24701-26899
Wisconsin: 53001-54999
Wyoming: 57717,82001-83199,83414

Creating custom ZIP code patterns

When you need to validate against specific format requirements that don't match standard country patterns, you can create custom formats using these placeholders:

  • (0): Any digit
  • (a): Lowercase letter
  • (A): Uppercase letter

This is especially useful for:

  • Custom internal codes
  • Special postal formats
  • Member ID validation

Example:

brixtemplates-zipcode-validator-list="(A)(A)(0)(0)

This would accept formats like "AB12" or "XY99", which might be useful for special routing codes or internal reference systems.

Final thoughts

Implementing proper ZIP code validation is more than just error prevention—it's about creating a smooth user experience while ensuring data quality. By following this guide, you've added a powerful tool to your Webflow forms that will help maintain data integrity and improve user satisfaction.

Need help implementing this solution, validating specific ZIP code formats, or setting up other custom form validation? Get in touch with our team for personalized assistance.

BRIX Templates Logo
About BRIX Templates

At BRIX Templates we craft beautiful, modern and easy to use Webflow templates & UI Kits.

Explore our Webflow templates
Join the conversation
Join our monthly Webflow email newsletter!

Receive one monthly email newsletter with the best articles, resources, tutorials, and free cloneables from BRIX Templates!

Webflow Newsletter
Thanks for joining our Webflow email newsletter
Oops! Something went wrong while submitting the form.
BRIX Templates - Email Newsletter with Webflow ResourcesBRIX Templates - Email NewsletterBRIX Templates - Webflow Email Newsletter
Webflow vs Framer: Which is better for your website in 2025?

Webflow vs Framer: Which is better for your website in 2025?

Choosing Webflow or Framer for 2025? Compare design, CMS, speed, learning curve & cost in our clear guide.

Apr 11, 2025
Webflow vs Wix: Which platform is better for your website in 2025?

Webflow vs Wix: Which platform is better for your website in 2025?

Webflow vs Wix? Compare Webflow’s design flexibility vs Wix’s ease-of-use to match your project’s needs.

Apr 11, 2025
Webflow vs HubSpot: Which platform is better in 2025?

Webflow vs HubSpot: Which platform is better in 2025?

Webflow or HubSpot in 2025? Compare design, SEO, performance, ease-of-use & pricing to find your ideal platform.

Apr 11, 2025