Chapter 14 - Improve validation

This commit is contained in:
2024-01-04 08:00:38 +01:00
parent 1c23830272
commit 69f0e86915
3 changed files with 52 additions and 15 deletions

View File

@@ -7,9 +7,11 @@ import {redirect} from "next/navigation";
const FormSchema = z.object({
id: z.string(),
customerId: z.string(),
amount: z.coerce.number(),
status: z.enum(['pending', 'paid']),
customerId: z.string({
invalid_type_error: 'Please select a customer.',
}),
amount: z.coerce.number().gt(0, { message: 'Please enter an amount greater than $0.' }),
status: z.enum(['pending', 'paid'], { invalid_type_error: 'Please select an invoice status'}),
date: z.string(),
});
@@ -17,14 +19,33 @@ const UpdateInvoice = FormSchema.omit({ id: true, date: true });
const CreateInvoice = FormSchema.omit({ id: true, date: true });
export async function createInvoice(formData: FormData) {
export type State = {
errors?: {
customerId?: string[];
amount?: string[];
status?: string[];
};
message?: string | null;
};
const { customerId, amount, status } = CreateInvoice.parse({
export async function createInvoice(prevState: State, formData: FormData) {
const validatedFields = CreateInvoice.safeParse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
});
// If form validation fails, return errors early. Otherwise, continue.
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to Create Invoice.',
};
}
const { customerId, amount, status } = validatedFields.data;
const amountInCents = amount * 100;
const date = new Date().toISOString().split('T')[0];