Form Validation
Elevate Web uses the zod library to validate forms. Zod is a TypeScript-first schema declaration and validation library. It is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations.
Benefits:
- Zero dependencies
- Works in Node.js and all modern browsers
- Tiny: 8kb minified + zipped
- Immutable: methods (e.g. .optional()) return a new instance
- Concise, chainable interface
- Functional approach: parse, don't validate
Usage
Create an object schema to represent your form's fields and apply desired validations.
export const SignupFormSchema = (i18n: LoginFormI18n) =>
z.object({
email: z
.string()
.email({ message: i18n.loginUserNameErrorDescription })
.trim(),
password: z
.string()
.min(3, { message: i18n.loginPasswordErrorDescription })
.trim(),
});
Send the form values to the schema for validation. Using Zod's safeParse method ensures validation results are returned without throwing exceptions. If validation fails, you can extract and return error messages:
const onSubmitForm = (state: FormState, formData: FormData) => {
const validatedFields = SignupFormSchema.safeParse({
email: formData.get('email'),
password: formData.get('password'),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
};
}
// Call the provider
};
Back in the form, you can use React's useFormStatus
hook to manage the form state and handle submission logic:
const [state, submit] = useFormState(login, undefined);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const formElement = e.target as HTMLFormElement;
const formData = new FormData(formElement);
submit(formData);
};