A zod schema for the marketing contact form.
npm install @transcend-io/contact-form-schema
import { zodResolver } from '@hookform/resolvers/zod';
import { ContactFormFields } from '@transcend-io/contact-form-schema';
import { useForm } from 'react-hook-form';
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(ContactFormFields),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('firstName')} />
{errors.firstName?.message && <p>{errors.firstName?.message}</p>}
<input {...register('email')} />
{errors.email?.message && <p>{errors.email?.message}</p>}
{/* ... */}
<input type="submit" />
</form>
);
};
import { ContactFormBody } from '@transcend-io/contact-form-schema';
export default async function contactFormHandler(
req: NextApiRequest,
res: NextApiResponse<ContactFormResponse>,
) {
// [[Perform authentication]]
// Validation
const result = ContactFormBody.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ error: result.error.message });
}
const contactFormBody = result.data;
// [[Perform business logic]]
}