mirror of
https://github.com/michivonah/nextjs.git
synced 2025-12-22 22:16:28 +01:00
add form validation
This commit is contained in:
parent
7d2dea886c
commit
eb75a90936
4 changed files with 93 additions and 14 deletions
|
|
@ -9,21 +9,42 @@ const sql = postgres(process.env.POSTGRES_URL!, {ssl: 'require'});
|
|||
|
||||
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(),
|
||||
});
|
||||
|
||||
const CreateInvoice = FormSchema.omit({id: true, date: true});
|
||||
|
||||
export async function createInvoice(formData: FormData){
|
||||
const { customerId, amount, status } = CreateInvoice.parse({
|
||||
export type State = {
|
||||
errors?: {
|
||||
customerId?: string[];
|
||||
amount?: string[];
|
||||
status?: string[];
|
||||
};
|
||||
message?: string | null;
|
||||
};
|
||||
|
||||
export async function createInvoice(prevState: State, formData: FormData){
|
||||
const validateFields = CreateInvoice.safeParse({
|
||||
customerId: formData.get('customerId'),
|
||||
amount: formData.get('amount'),
|
||||
status: formData.get('status'),
|
||||
});
|
||||
|
||||
if(!validateFields.success){
|
||||
return{
|
||||
errors: validateFields.error.flatten().fieldErrors,
|
||||
message: 'Missing fields. Failed to create invoice.',
|
||||
}
|
||||
}
|
||||
|
||||
const { customerId, amount, status } = validateFields.data;
|
||||
const amountInCents = amount * 100;
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue