Validating Credit Card Form

Anonymous

Create a validation for the Credit Card form that accepts most of the card networks with Card number, CVV, Holder name and Expiry.

ZodGPT logo
ZodGPT

Sure, let's create a Zod schema for a credit card form that validates the Card Number, CVV, Holder Name, and Expiry Date. Each field will have its own specific validation rules. Here's how you can do it:

  1. Card Number: We'll validate this as a string and use a regex to ensure it matches the general pattern of credit card numbers (which is typically 16 digits, although it can vary between 13 to 19 digits in reality). For simplicity, we'll stick to a basic 16-digit check.

  2. CVV: This is typically a 3 or 4 digit number. We'll use a regex to ensure it's either 3 or 4 digits.

  3. Holder Name: We'll validate this as a non-empty string. Additional checks can be added based on specific requirements.

  4. Expiry Date: This can be validated in various ways. For simplicity, we'll expect a string in the format "MM/YY" and use a regex to validate this format.

Here's the TypeScript code using Zod:

typescript
1import { z } from "zod"; 2 3const creditCardSchema = z.object({ 4 cardNumber: z.string().regex(/^\d{16}$/, "Card number must be 16 digits"), 5 cvv: z.string().regex(/^\d{3,4}$/, "CVV must be 3 or 4 digits"), 6 holderName: z.string().min(1, "Holder name is required"), 7 expiryDate: z.string().regex(/^(0[1-9]|1[0-2])\/\d{2}$/, "Expiry date must be in MM/YY format"), 8}); 9 10type CreditCard = z.infer<typeof creditCardSchema>; 11 12// Example usage 13const exampleCard: CreditCard = { 14 cardNumber: "1234567890123456", 15 cvv: "123", 16 holderName: "John Doe", 17 expiryDate: "12/25", 18}; 19 20creditCardSchema.parse(exampleCard); // This will validate the example card

This schema will validate that:

  • The card number is 16 digits.
  • The CVV is 3 or 4 digits.
  • The holder name is not empty.
  • The expiry date is in the "MM/YY" format.

You can adjust the regex patterns and validation rules based on your specific requirements for different card networks or other constraints.