Skip to content

Promo Code Check ​

A promo code that the server checks when the customer leaves the field.

Live exampleA check only the server can answer

Try welcome10 or freeship. Any other code is not valid.

Type a code and leave the field to start the check, or press Enter, and the submit waits until the check has finished.

vue
<script setup lang="ts">
import { useField, useForm } from '@formtree/vue'
import { ref } from 'vue'

import { promoCodeField } from '../forms/promo-code'

const form = useForm(promoCodeField, { deps: { cartId: 'cart_42' } })
const code = useField(form)

const applied = ref<string>()

const apply = form.handleSubmit(value => {
  applied.value = value
})
</script>

<template>
  <form class="demo-form" novalidate @submit.prevent="apply">
    <div class="demo-field">
      <label :for="code.id">Promo code</label>
      <div class="demo-row">
        <input
          v-model="code.model"
          v-bind="code.attrs"
          autocomplete="off"
          style="flex: 1"
        />
        <button type="submit">Apply</button>
      </div>
      <p :id="code.errorId" class="demo-error">
        {{ code.state.requesting ? 'Checking…' : code.errorMessage }}
      </p>
    </div>
    <p class="demo-hint">
      Try welcome10 or freeship. Any other code is not valid.
    </p>
    <p v-if="applied" class="demo-hint">Applied {{ applied }}</p>
  </form>
</template>
ts
import { defineFieldWithDeps } from '@formtree/core'
import { z } from 'zod'

import { checkPromoCode } from './api'

export const promoCodeField = defineFieldWithDeps<{ cartId: string }>()({
  schema: z.string().trim().toUpperCase().optional(),
  validateAsync: {
    on: 'blur',
    run: async (code, { signal, deps }) => {
      if (code == undefined || code == '') {
        return undefined
      }
      const valid = await checkPromoCode(
        { code, cartId: deps.cartId },
        signal,
      )
      return valid ? undefined : { code: 'This code is not valid' }
    },
  },
})
ts
const LATENCY_MS = 400

const VALID_PROMO_CODES = ['WELCOME10', 'FREESHIP']

export const SHIPPING_COUNTRIES = ['DE', 'NL', 'TR', 'US']

export const ATTRIBUTES = [
  { id: 'country', label: 'Country' },
  { id: 'plan', label: 'Plan' },
  { id: 'device', label: 'Device' },
]

export interface PromoCodeCheck {
  readonly code: string
  readonly cartId: string
}

export interface AddressCheck {
  readonly street: string
  readonly postalCode: string
  readonly country: string
}

export interface LineItemRequest {
  readonly id?: number
  readonly sku: string
  readonly quantity: number
}

export interface SavedLineItem {
  readonly id: number
  readonly sku: string
  readonly quantity: number
}

export interface ContactMessage {
  readonly name: string
  readonly email: string
  readonly message: string
}

let lastLineItemId = 100

export async function checkPromoCode(
  check: PromoCodeCheck,
  signal?: AbortSignal,
): Promise<boolean> {
  await delay(signal)
  return VALID_PROMO_CODES.includes(check.code)
}

export async function verifyAddress(
  address: AddressCheck,
  signal?: AbortSignal,
): Promise<boolean> {
  await delay(signal)
  return /\d/.test(address.street)
}

export async function saveLineItem(
  item: LineItemRequest,
): Promise<SavedLineItem> {
  await delay()
  lastLineItemId += 1
  return {
    id: item.id ?? lastLineItemId,
    sku: item.sku,
    quantity: item.quantity,
  }
}

export async function updatePrice(price: number): Promise<number> {
  await delay()
  return price
}

export async function sendMessage(
  contact: ContactMessage,
): Promise<ContactMessage> {
  await delay()
  return contact
}

function delay(signal?: AbortSignal): Promise<void> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(resolve, LATENCY_MS)
    signal?.addEventListener('abort', () => {
      clearTimeout(timer)
      reject(signal.reason)
    })
  })
}

Released under the MIT License.