Checkout Validation
Card (Luhn), expiry, CVC, email, phone and required-field checks, input formatters and a per-country postal code validator.
npx shadcn@latest add https://ui.develop-better-solutions.com/r/commerce-validation.jsonUsage
commerce-validation-example.tsx
"use client";
import { useState } from "react";
import {
createPostalValidator,
formatCardNumber,
formatExpiry,
validateCardNumber,
validateCvc,
validateEmail,
validateExpiry,
validatePhone,
} from "@dbs/ui";
const validatePostal = createPostalValidator({
countries: [
{ code: "MA", label: "Morocco", regionLabel: "Region", postalLabel: "Postal code", hint: "20000" },
{ code: "FR", label: "France", regionLabel: "Region", postalLabel: "Postal code", hint: "75001" },
],
patterns: { MA: /^\d{5}$/, FR: /^\d{5}$/ },
});
export default function CommerceValidationExample() {
const [v, setV] = useState({ email: "amine@", card: "4242424242424241", expiry: "0120", cvc: "12", phone: "06 12", postal: "2000" });
const set = (k: keyof typeof v, value: string) => setV((s) => ({ ...s, [k]: value }));
const rows: [string, keyof typeof v, string | null][] = [
["Email", "email", validateEmail(v.email)],
["Card number", "card", validateCardNumber(v.card)],
["Expiry (MMYY)", "expiry", validateExpiry(formatExpiry(v.expiry))],
["CVC", "cvc", validateCvc(v.cvc)],
["Phone", "phone", validatePhone(v.phone)],
["Postal code (MA)", "postal", validatePostal("MA", v.postal)],
];
return (
<div className="flex w-full max-w-xl flex-col gap-3 text-sm">
{rows.map(([label, key, error]) => (
<label key={key} className="grid gap-1 sm:grid-cols-[9rem_1fr_1fr] sm:items-center sm:gap-3">
<span className="text-ink-muted">{label}</span>
<input
value={key === "card" ? formatCardNumber(v.card) : v[key]}
onChange={(e) => set(key, e.target.value)}
className="h-10 rounded-lg border border-line bg-canvas px-3"
/>
<span className={error ? "text-orange" : "text-ink-subtle"}>{error ?? "Valid"}</span>
</label>
))}
</div>
);
}