From 41884d72985ecfcc864f74e122548dcd287f20c8 Mon Sep 17 00:00:00 2001 From: Vinicius Souza Date: Wed, 6 Nov 2024 17:50:26 +0000 Subject: [PATCH] feat: add form validation --- src/screens/Profile.tsx | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/src/screens/Profile.tsx b/src/screens/Profile.tsx index b26c860..6e59230 100644 --- a/src/screens/Profile.tsx +++ b/src/screens/Profile.tsx @@ -3,15 +3,17 @@ import { ScrollView, TouchableOpacity } from 'react-native'; import { Center, Heading, Text, useToast, VStack } from '@gluestack-ui/themed'; import * as ImagePicker from 'expo-image-picker'; import * as FileSystem from 'expo-file-system'; - +import * as yup from 'yup'; import { Controller, useForm } from 'react-hook-form'; +import { yupResolver } from '@hookform/resolvers/yup'; + +import { useAuth } from '@hooks/useAuth'; import { Button } from '@components/Button'; import { Input } from '@components/Input'; import { ScreenHeader } from '@components/ScreenHeader'; import { UserPhoto } from '@components/UserPhoto'; import { ToastMessage } from '@components/ToastMessage'; -import { useAuth } from '@hooks/useAuth'; type ProfileForm = { name: string; @@ -21,13 +23,35 @@ type ProfileForm = { confirm_password: string; }; +const profileSchema = yup.object({ + name: yup.string().required('Informe o nome.'), + new_password: yup + .string() + .min(8, 'Senha deve ter no mínimo 8 caracteres.') + .nullable() + .transform((value) => (!!value ? value : null)), + confirm_password: yup + .string() + .nullable() + .transform((value) => (!!value ? value : null)) + .oneOf([yup.ref('new_password'), null], 'Senhas não coincidem.') + .when('new_password', { + is: (field: any) => field, + then: yup.string().nullable().required('Senhas não coincidem'), + }), +}); + export function Profile() { const [userPhoto, setUserPhoto] = useState('https://i.pravatar.cc/200'); const toast = useToast(); const { user } = useAuth(); - const { control, handleSubmit } = useForm({ + const { + control, + handleSubmit, + formState: { errors }, + } = useForm({ defaultValues: { name: user.name, email: user.email, @@ -35,6 +59,7 @@ export function Profile() { new_password: '', confirm_password: '', }, + resolver: yupResolver(profileSchema), }); async function handleProfileUpdate(data: ProfileForm) { @@ -106,7 +131,13 @@ export function Profile() { control={control} name="name" render={({ field: { onChange, value } }) => ( - + )} /> @@ -146,6 +177,7 @@ export function Profile() { bg="$gray600" secureTextEntry onChangeText={onChange} + errorMessage={errors.new_password?.message} /> )} /> @@ -159,6 +191,7 @@ export function Profile() { bg="$gray600" secureTextEntry onChangeText={onChange} + errorMessage={errors.confirm_password?.message} /> )} />