feat: add zod validation for role and user forms

This commit is contained in:
2026-06-17 12:05:43 +05:30
parent bd0782a55f
commit 9bb740e446
10 changed files with 270 additions and 108 deletions

View File

@@ -1,14 +1,12 @@
'use client';
import { useRef, type ComponentProps } from 'react';
import type { UseFormRegister } from 'react-hook-form';
import type { FieldErrors, UseFormRegister, UseFormReturn } from 'react-hook-form';
import { Loader2 } from 'lucide-react';
import { FormField } from '@/components/form';
import { RoleCombobox } from '@/components/lookups/RoleCombobox';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
@@ -17,49 +15,42 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import type { UserFormValues } from '../hooks/useUserForm';
interface UserSheetProps {
open: boolean;
onOpenChange: (open: boolean) => void;
userId?: number;
register: UseFormRegister<UserFormValues>;
errors: FieldErrors<UserFormValues>;
touchedFields: UseFormReturn<UserFormValues>['formState']['touchedFields'];
onSubmit: ComponentProps<'form'>['onSubmit'];
roleId: string;
onRoleChange: (roleId: string) => void;
canSubmit: boolean;
isSaving: boolean;
}
export function UserSheet({
open,
onOpenChange,
userId,
register,
errors,
touchedFields,
onSubmit,
roleId,
onRoleChange,
canSubmit,
isSaving,
}: UserSheetProps) {
const roleComboboxPortalRef = useRef<HTMLDivElement | null>(null);
const firstNameErrorMessage = touchedFields.first_name ? errors.first_name?.message : undefined;
const lastNameErrorMessage = touchedFields.last_name ? errors.last_name?.message : undefined;
const emailErrorMessage = touchedFields.email ? errors.email?.message : undefined;
const phoneErrorMessage = touchedFields.phone_number ? errors.phone_number?.message : undefined;
const roleErrorMessage = touchedFields.role_id ? errors.role_id?.message : undefined;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -72,54 +63,63 @@ export function UserSheet({
<form onSubmit={onSubmit} className="flex flex-1 flex-col gap-5 px-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="first-name">First Name</Label>
<FormField
id="first-name"
label="First Name"
required
error={firstNameErrorMessage}
>
<Input
id="first-name"
placeholder="Enter first name"
{...register('first_name', { required: true })}
required
aria-invalid={!!firstNameErrorMessage}
{...register('first_name')}
/>
</div>
<div className="space-y-2">
<Label htmlFor="last-name">Last Name</Label>
</FormField>
<FormField
id="last-name"
label="Last Name"
required
error={lastNameErrorMessage}
>
<Input
id="last-name"
placeholder="Enter last name"
{...register('last_name', { required: true })}
required
aria-invalid={!!lastNameErrorMessage}
{...register('last_name')}
/>
</div>
</FormField>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<FormField
id="email"
label="Email"
required
error={emailErrorMessage}
>
<Input
id="email"
type="email"
placeholder="name@example.com"
{...register('email', { required: true })}
required
aria-invalid={!!emailErrorMessage}
{...register('email')}
/>
</div>
<div className="space-y-2">
<Label htmlFor="phone-number">Phone Number</Label>
</FormField>
<FormField
id="phone-number"
label="Phone Number"
error={phoneErrorMessage}
>
<Input
id="phone-number"
placeholder="Enter phone number"
placeholder="+919876543210"
aria-invalid={!!phoneErrorMessage}
{...register('phone_number')}
/>
</div>
<div className="space-y-2">
<Label>Role</Label>
</FormField>
<FormField label="Role" required error={roleErrorMessage}>
<RoleCombobox
value={roleId}
onValueChange={onRoleChange}
@@ -132,11 +132,11 @@ export function UserSheet({
<input
type="hidden"
{...register('role_id', { required: true })}
{...register('role_id')}
value={roleId}
readOnly
/>
</div>
</FormField>
<DialogFooter className="px-0">
<Button
@@ -148,7 +148,7 @@ export function UserSheet({
Cancel
</Button>
<Button type="submit" disabled={isSaving}>
<Button type="submit" disabled={isSaving || !canSubmit}>
{isSaving ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
{userId ? 'Update User' : 'Create User'}

View File

@@ -1,20 +1,31 @@
'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { useCallback } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import type { AdministrationUser } from '@/types';
import { useSaveUserMutation } from './useUserMutations';
export interface UserFormValues {
id?: number;
first_name: string;
last_name: string;
email: string;
phone_number: string;
role_id: string;
}
const optionalPhoneSchema = z
.string()
.trim()
.refine((value) => value === '' || /^\+(?:[0-9] ?){6,14}[0-9]$/.test(value), {
message: 'Please enter a valid phone number',
});
const userFormSchema = z.object({
id: z.number().optional(),
first_name: z.string().trim().min(1, 'First name is required'),
last_name: z.string().trim().min(1, 'Last name is required'),
email: z.string().trim().min(1, 'Email is required').email('Invalid email'),
phone_number: optionalPhoneSchema,
role_id: z.string().trim().min(1, 'Role is required'),
});
export type UserFormValues = z.infer<typeof userFormSchema>;
const defaultValues: UserFormValues = {
first_name: '',
@@ -31,9 +42,12 @@ export function useUserForm({ onSaved }: { onSaved: () => void }) {
handleSubmit: submitForm,
reset,
setValue,
formState: { isSubmitting, errors },
formState: { errors, isSubmitting, touchedFields },
} = useForm<UserFormValues>({
defaultValues,
mode: 'onTouched',
reValidateMode: 'onChange',
resolver: zodResolver(userFormSchema),
});
const saveMutation = useSaveUserMutation({
onSaved: () => {
@@ -44,16 +58,39 @@ export function useUserForm({ onSaved }: { onSaved: () => void }) {
const userId = useWatch({ control, name: 'id' });
const roleId = useWatch({ control, name: 'role_id' }) || '';
const firstName = useWatch({ control, name: 'first_name' }) || '';
const lastName = useWatch({ control, name: 'last_name' }) || '';
const email = useWatch({ control, name: 'email' }) || '';
const phoneNumber = useWatch({ control, name: 'phone_number' }) || '';
const isPhoneValid = phoneNumber.trim() === '' || /^\+(?:[0-9] ?){6,14}[0-9]$/.test(phoneNumber.trim());
const canSubmit =
firstName.trim().length > 0 &&
lastName.trim().length > 0 &&
email.trim().length > 0 &&
roleId.trim().length > 0 &&
isPhoneValid;
const handleSubmit = submitForm(
(values) => saveMutation.mutate(values),
(formErrors) => {
if (formErrors.first_name || formErrors.last_name || formErrors.email) {
toast.error('First name, last name and email are required');
if (formErrors.first_name?.message) {
toast.error(formErrors.first_name.message);
return;
}
if (formErrors.role_id) {
toast.error('Select a role');
if (formErrors.last_name?.message) {
toast.error(formErrors.last_name.message);
return;
}
if (formErrors.email?.message) {
toast.error(formErrors.email.message);
return;
}
if (formErrors.phone_number?.message) {
toast.error(formErrors.phone_number.message);
return;
}
if (formErrors.role_id?.message) {
toast.error(formErrors.role_id.message);
}
},
);
@@ -94,6 +131,8 @@ export function useUserForm({ onSaved }: { onSaved: () => void }) {
roleId,
userId,
errors,
touchedFields,
canSubmit,
isSaving: isSubmitting || saveMutation.isPending,
};
}

View File

@@ -54,6 +54,9 @@ export default function UsersPage() {
userId,
roleId,
setRoleId,
errors,
touchedFields,
canSubmit,
isSaving,
} = userForm;
const statusMutation = useUserStatusMutation();
@@ -145,9 +148,12 @@ export default function UsersPage() {
onOpenChange={setIsSheetOpen}
userId={userId}
register={register}
errors={errors}
touchedFields={touchedFields}
onSubmit={handleSubmit}
roleId={roleId}
onRoleChange={setRoleId}
canSubmit={canSubmit}
isSaving={isSaving}
/>
</>