import :
import Button from '@mui/material/Button';
import "@/assets/scss/components/form.scss";
validate form:
import { Form, Field } from "@/components/hook-form";
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z as zod } from "zod/v4";
schema : setting form example
Defining schemas : https://zod.dev/api
const
FormSchema = zod.object({
// Defining schemas
name: zod.string().min(
1, { message: 'กรุณากรอก ชื่อ-นามสกุล!'}
) ,
mail: zod.string().min(
1, { message: 'กรุณากรอก อีเมล!'}
).email({
pattern: zod.regexes.email ,
message: 'กรุณากรอก อีเมลให้ถูกต้อง!',
}) ,
subject: zod.string().min(
1, { message: 'กรุณากรอก เรื่องที่ต้องการแจ้ง!'}
) ,
phone: zod.string().min(
1, { message: 'กรุณากรอก เบอร์โทรศัพท์!'}
).refine((value) =>
/^[0]{1}(?:[0-9-() /.]\s?) {8}[0-9]{1}$/.test(value) ,
{ message: 'กรุณากรอก เบอร์โทรศัพท์ให้ถูกต้อง!'}
) ,
topic: zod.string().min(
1, { message: 'กรุณากรอก หัวข้อ!'}
) ,
// .optional() ใส่เพื่อไม่บังคับกรอก
});
type FormSchemaType = zod.infer < typeof FormSchema >
validate useForm : example
// in function pageconst methods = useForm<FormSchemaType>({
mode: 'onSubmit',
resolver: zodResolver(FormSchema),
defaultValues: {
name: '',
mail: '',
subject: '',
phone: '',
topic: '',
},
});
const{ watch, handleSubmit,} = methods;
const value = watch()
console.log(value);
const onSubmit = handleSubmit((data) => {
try {
console.log(data);
} catch (error) {
console.log(error);
}
}data);
dom : example
<Form methods={methods} onSubmit={onSubmit}>
<fieldset className="form-fieldset">
<legend className="form-legend text-center">
แบบฟอร์มตัวอย่าง
</legend>
<div className="form-group">
<div className="col">
<Field.Text name="name" label="ชื่อ-นามสกุล" required/>
</div>
</div>
<div className="form-group">
<div className="col">
<Field.Text name="mail" label="อีเมล" required/>
</div>
</div>
<div className="form-group">
<div className="col">
<Field.Text name="subject" label="เรื่องที่ต้องการแจ้ง" required/>
</div>
</div>
<div className="form-group">
<div className="col">
<Field.Text name="phone" label="เบอร์โทรศัพท์" required maxLength={10} type="number" />
</div>
</div>
<div className="form-group">
<div className="col">
<Field.Text name="topic" label="หัวข้อ" required/>
</div>
</div>
<div className="form-group">
<div className="col">
<FormControl fullWidth>
<FormLabel htmlFor="info">รายละเอียด</FormLabel>
<textarea id="info" rows={3} style={{ width: '100%' }} />
</FormControl>
</div>
</div>
<Box className="form-action">
<Button type="submit" variant="contained" color="secondary" size="medium">
ส่ง
</Button>
</Box>
</fieldset>
</Form>