Add Country and State Fields to an Address or Checkout Form
A shopper changes their shipping country from the US to Canada. If the checkout keeps California selected or keeps asking for a US ZIP code, the shopper has to fix a form that should have adapted. Start by making the country drive the region choices and the rules for the rest of the address.
The website form guide covers the shared snippet, public key and allowed domains.
What you need
Use a checkout or address form whose fields and handler you control. Set up a CountriesDB project with a public key and allow the checkout hostname. Decide which countries you serve and which ones require a region before you design the fields.
Set up the address fields
1. Ask for the country first
Put the country above the region, city and postal code so the form can apply the destination's rules. Use shipping-specific names and IDs if billing has its own fields. Keep the region optional in the HTML and apply requiredness per destination. Some addresses do not need a region.
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>
<label for="shipping-country">Country</label>
<select id="shipping-country" name="shipping_country" class="country-selection"
data-name="shipping-country" data-label="Select country" data-preselected="" required></select>
<label for="shipping-region">State / province / region</label>
<select id="shipping-region" name="shipping_region" class="subdivision-selection"
data-country="shipping-country" data-label="Select region" data-prefer-official></select>
2. Recalculate when the destination changes
Clear the previous region when the country changes and update any shipping or tax calculation based on the new destination. Match the widget's offered countries to your shipping coverage using the widget filter options, and enforce coverage on the server as well.
3. Check what reaches your server
Submit two test orders with different country and region combinations. Confirm the handler receives the codes it expects, such as US and US-CA for an ISO configuration, and rejects a region from a different country. Also test a destination where the region can be left blank. Use the validation guide to decide whether postal address verification is also needed.
FAQ
Do I need a developer?
Most checkouts need one to connect these fields to saved addresses, shipping and server-side rules.
Should state or province always be required?
Apply that rule per destination. A global requirement can block valid addresses.
Can I reuse these IDs for billing?
Give billing its own IDs and field names. If both pairs are on one page, use the widget docs to configure and test multiple instances before shipping.
Does a valid country and region establish deliverability?
It establishes a valid geographic pair. Postal checks and carrier eligibility require their own rules.