src/shipping-address-api.tsTypeScript
@@ -0,0 +1,32 @@
1+
export interface AddressValues {2+
street: string;3+
country: "US" | "CA";4+
postalCode: string;5+
}6+
7+
export type AddressErrors = Partial<Record<keyof AddressValues, string>>;8+
9+
export type AddressApiResponse =10+
| { kind: "validation"; errors: AddressErrors; values: AddressValues }11+
| { kind: "accepted"; redirectTo: "/checkout/review" };12+
13+
const US_POSTAL_CODE = /^\d{5}$/;14+
const CA_POSTAL_CODE = /^[A-Z]\d[A-Z] \d[A-Z]\d$/i;15+
16+
export function validateShippingAddress(values: AddressValues): AddressErrors {17+
const errors: AddressErrors = {};18+
19+
if (!values.street.trim()) {20+
errors.street = "Enter a street address.";21+
}22+
23+
const validPostalCode =24+
values.country === "US"25+
? US_POSTAL_CODE.test(values.postalCode)26+
: CA_POSTAL_CODE.test(values.postalCode);27+
if (!validPostalCode) {28+
errors.postalCode = `Enter a valid ${values.country} postal code.`;29+
}30+
31+
return errors;32+
}