Files
fire-exam/src/widgets/offer-form/ui.tsx
2025-06-18 15:41:16 +03:00

100 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use client';
import s from './styles.module.scss';
import { Button, Input, PhoneInput } from '@shared/ui';
import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import toast from 'react-hot-toast';
import { sendFormFn } from '@shared/api/api.service';
import { isValidPhoneNumber } from 'libphonenumber-js/min';
import Link from 'next/link';
const FormSchema = z.object({
name: z
.string()
.min(3, { message: 'Поле должно содержать не менее 3-х букв' })
.regex(/^[A-Za-zА-Яа-яЁё]+(?:[ '-][A-Za-zА-Яа-яЁё]+)*$/, {
message: 'Поле содержит некорректные символы',
}),
phone: z.string().refine(isValidPhoneNumber, 'Некорректный номер телефона'),
});
type TForm = z.infer<typeof FormSchema>;
const defaultValues = {
name: '',
phone: '',
};
export default function OfferForm() {
const {
handleSubmit,
control,
reset,
clearErrors,
formState: { errors },
} = useForm<TForm>({
resolver: zodResolver(FormSchema),
defaultValues,
});
const onSubmit = async (data: TForm) => {
const payload = {
...data,
form: 'offer-form',
};
try {
await sendFormFn(payload);
toast.success('Заявка на консультацию принята');
reset(defaultValues);
} catch (e) {
toast.error('Ошибка при отправке заявки...', {
duration: 3000,
});
}
};
return (
<form className={s.RowForm} onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name={'name'}
render={({ field }) => (
<Input
{...field}
className={s.Unit}
type='text'
placeholder='Ваше имя'
error={errors && errors.name?.message}
onChange={(e) => {
clearErrors('name');
field.onChange(e);
}}
/>
)}
/>
<Controller
control={control}
name={'phone'}
render={({ field }) => (
<PhoneInput
{...field}
className={s.Unit}
type='text'
placeholder='+7 999 123-45-67'
error={errors && errors.phone?.message}
onChange={(e) => {
clearErrors('phone');
field.onChange(e);
}}
/>
)}
/>
<Button className={s.Unit} variant='orange'>
Получить консультацию
</Button>
</form>
);
}