Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 61 ยท Cart, Checkout and Customer Pages

Forms: Contact, Newsletter and Custom Forms

Learn the Liquid form tag: contact and newsletter forms, form.errors and posted_successfully, accessible error messages, spam protection and when to use Shopify Forms.

Almost every store needs a few forms: a contact page, a newsletter signup in the footer, a login box, a product form that adds to the cart. Shopify gives you one tag for all of them, {% form %}. It writes the correct action and method, adds the hidden fields Shopify needs to accept the post, and exposes a form object so you can show errors and success messages on the same page.

This lesson covers the form tag types, the two forms you will build most often (contact and newsletter), how to read form.errors and form.posted_successfully?, how to make error messages accessible, and what to do about spam. It builds on Customer Accounts and Account Pages, which uses the same tag for login and registration.

The form tag and the form object exist only on Shopify, so the theme code in this lesson is read-only and targets current Online Store 2.0 themes. The runnable stand-ins are plain JavaScript functions that play the part of Shopify's server: they validate fields, build the error list and print the data a submission would carry. They do not send anything anywhere.

The form tag and its types

You always pass a type as the first argument. The type decides where the post goes and what the form object contains.

LIQUID
{% form 'contact', id: 'ContactForm', class: 'contact-form' %}
  ...
{% endform %}

Extra arguments after the type become HTML attributes on the generated <form> element, so id, class and novalidate all work. Frequently used types:

Type Used for
contact the contact form (emails the merchant)
customer newsletter signup and other marketing contact creation
customer_login, create_customer, recover_customer_password, reset_customer_password, activate_customer_password, customer_address account pages
product the add-to-cart form, see The Product Form and Add to Cart
localization the language and country selectors
new_comment blog article comments
guest_login letting a shopper without an account follow an order

Do not write your own <form action="/contact" method="post">. Without the tag you lose the hidden fields, the spam checks and the redirect behavior, and the post is often rejected.

A contact form

The contact form sends an email to the store's customer email address. Field names follow the pattern contact[...]. The three standard ones are contact[name], contact[email] and contact[body]. Anything else you add (a phone number, an order number) is included in the email body under the name you give it.

LIQUID
{% form 'contact', id: 'ContactForm', novalidate: 'novalidate' %}
  {%- if form.posted_successfully? -%}
    <p role="status" tabindex="-1" id="ContactSuccess">
      Thanks. We will answer within one business day.
    </p>
  {%- endif -%}

  {%- if form.errors -%}
    <div role="alert" tabindex="-1" id="ContactErrors">
      <h2>Please fix the following</h2>
      <ul>
        {%- for field in form.errors -%}
          <li>
            <a href="#ContactForm-{{ field }}">
              {{ form.errors.translated_fields[field] | capitalize }}
              {{ form.errors.messages[field] }}
            </a>
          </li>
        {%- endfor -%}
      </ul>
    </div>
  {%- endif -%}

  <label for="ContactForm-name">Name</label>
  <input id="ContactForm-name" name="contact[name]" type="text"
         autocomplete="name" value="{{ form.name }}">

  <label for="ContactForm-email">Email <span aria-hidden="true">*</span></label>
  <input id="ContactForm-email" name="contact[email]" type="email"
         autocomplete="email" required value="{{ form.email }}"
         {% if form.errors contains 'email' %}aria-invalid="true"{% endif %}>

  <label for="ContactForm-phone">Phone (optional)</label>
  <input id="ContactForm-phone" name="contact[phone]" type="tel"
         autocomplete="tel" value="{{ form.phone }}">

  <label for="ContactForm-body">Message</label>
  <textarea id="ContactForm-body" name="contact[body]" rows="6" required>{{ form.body }}</textarea>

  <button type="submit">Send</button>
{% endform %}

Three details matter here. First, after a failed post Shopify re-renders the page and fills form.name, form.email and so on, so you can put the shopper's text back into the fields instead of making them type it again. Second, the page is the same URL, so a successful post ends with form.posted_successfully? returning true; the check uses a question mark because it is the actual method name. Third, form.errors is a list of field names that failed (such as email), with form.errors.messages giving the message text and form.errors.translated_fields the human-readable field label in the shopper's language.

A newsletter signup

A newsletter box is a customer form that creates (or updates) a customer record with a marketing tag. It needs an email, and a hidden tag field so the merchant can find these contacts later.

LIQUID
{% form 'customer', id: 'Newsletter', class: 'newsletter' %}
  <input type="hidden" name="contact[tags]" value="newsletter">

  <label for="Newsletter-email" class="visually-hidden">Email address</label>
  <input id="Newsletter-email" name="contact[email]" type="email"
         autocomplete="email" required placeholder="[email protected]"
         {% if form.errors %}aria-invalid="true" aria-describedby="Newsletter-error"{% endif %}>

  {%- if form.errors -%}
    <p id="Newsletter-error" role="alert">
      {{ form.errors.translated_fields.email | capitalize }} {{ form.errors.messages.email }}
    </p>
  {%- endif -%}

  <button type="submit">Subscribe</button>

  {%- if form.posted_successfully? -%}
    <p role="status">Thanks for subscribing.</p>
  {%- endif -%}
{% endform %}

Whether the person becomes an email subscriber is controlled by the store's marketing settings and consent rules, which depend on the region. Do not promise "you are now subscribed" in a way that contradicts the store's confirmation flow; "Thanks for signing up" is safer. For the legal side of consent and email see Privacy and Compliance.

Because the footer appears on every page, a newsletter form usually lives in a section that is rendered on all of them. If more than one form of the same type appears on a page, each needs its own unique id. Duplicate ids break the <label for> links and the error anchors.

Accessible errors

Error handling is where most theme forms fail users. A short checklist:

  • put the error summary in an element with role="alert" (or move focus to it) so a screen reader announces it;
  • link each error to its field with an anchor (href="#ContactForm-email") and give every input a real <label> connected by for/id;
  • mark the failed fields with aria-invalid="true" and connect a message with aria-describedby;
  • do not rely on color alone, and never replace the label with a placeholder;
  • keep the shopper's typed values.

More on this in Accessibility in Themes. Because a failed post reloads the page, your code can also scroll to or focus the error box on load. A short script that finds #ContactErrors and calls focus() is enough, and the tabindex="-1" attribute makes that element focusable without adding it to the tab order.

Spam protection

You do not write a CAPTCHA. Shopify screens contact, customer and comment forms on its servers, and if a post looks suspicious it can show an hCaptcha challenge page before accepting it. Two practical consequences:

  1. Do not remove the hidden fields the tag adds, and do not try to submit these forms from your own server.
  2. A honeypot field or your own client-side check is optional extra hygiene, but never a replacement. Anything your browser code checks can be skipped by a script that posts directly, which is why the checks must be repeated on the server side. The same idea is explained in Shop Security.

For a form that must not accept junk, keep fields to the minimum and validate with the browser's built-in attributes (required, type="email", maxlength, pattern). Add novalidate only when you provide your own, better messages.

Shopify Forms and other options

If the merchant needs more than your theme provides (many fields, conditional logic, file uploads, a results inbox), do not build it yourself. Shopify Forms is a Shopify app that adds forms as theme blocks and stores submissions in the admin. Your job as a theme developer is to make sure the theme supports app blocks in the sections where forms may appear, as described in App Blocks and App Embeds. If you need to store a submission as data, or send it somewhere else, you are in app territory: a custom form can post with JavaScript to an app proxy or another endpoint, but that is an app's job, not a theme's.

Stand-in: validate and print a contact submission

This function plays the part of Shopify's server for the contact form above. It trims input, collects errors in the same fields -> messages shape the template loops over, and returns what a successful submission would carry.

JS Stand-in: contact form validation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first post fails twice, and the error list matches what the Liquid loop prints. The second passes, and its values have been trimmed. In the real tag, Shopify does this work and re-renders your template.

Stand-in: build the error summary safely

Error messages and echoed values come from the shopper, so they must be escaped before they go into HTML. Liquid output with {{ }} does not escape text for you, so use the escape filter on echoed text. This stand-in builds the summary markup and shows why escaping matters.

JS Stand-in: accessible error summary with escaping

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The unsafe line closes the attribute and injects a script tag. In a theme, {{ form.email | escape }} gives the safe version. Read more in Security in Themes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use {% form 'contact' %} instead of writing a plain <form action="/contact">?

    The tag writes the action and method, adds the hidden fields Shopify requires and enables its server-side checks. A hand-written form is usually rejected.
  2. 2. How does the template know a submission succeeded?

    After a successful post the same page renders again and form.posted_successfully? is true, so the template can show a confirmation.
  3. 3. Which pair makes an error message reachable by assistive technology?

    An alert region is announced, and aria-invalid together with a linked message tells users which field failed and why. Color or placeholders alone are not enough.
  4. 4. A newsletter form needs to tag new contacts so the merchant can find them. How is that done?

    The customer form accepts a contact[tags] field, so a hidden input with a value such as newsletter tags the new contact.
  5. 5. When is Shopify Forms (the app) a better choice than a hand-built form?

    Rich forms with storage and logic are an app's job. The theme only has to support app blocks where such forms may be placed.

Summary

  • Use {% form 'type' %} for every Shopify form; it supplies the action, hidden fields and server-side checks.
  • Contact forms use contact[name], contact[email] and contact[body]; newsletter signups use the customer type with a hidden contact[tags] field.
  • Read form.posted_successfully?, form.errors, form.errors.messages and form.errors.translated_fields, and re-fill fields from the form object.
  • Make errors accessible with role="alert", linked anchors, real labels and aria-invalid, and escape anything echoed back.
  • Spam protection happens on Shopify's servers; use Shopify Forms or an app for complex needs.

Next, move from pages to scripting in JavaScript in Themes: Web Components and Events.