Skip to content

Commit

Permalink
13 - Validation of the forms
Browse files Browse the repository at this point in the history
  • Loading branch information
felipemarinhodev committed May 24, 2020
1 parent cff1436 commit ec17e55
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 12 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"react-native-safe-area-context": "^2.0.0",
"react-native-screens": "^2.8.0",
"react-native-vector-icons": "^6.6.0",
"styled-components": "^5.1.0"
"styled-components": "^5.1.0",
"yup": "^0.29.0"
},
"devDependencies": {
"@babel/core": "^7.6.2",
Expand All @@ -34,6 +35,7 @@
"@types/react-native-vector-icons": "^6.4.5",
"@types/react-test-renderer": "16.9.2",
"@types/styled-components": "^5.1.0",
"@types/yup": "^0.29.0",
"@typescript-eslint/eslint-plugin": "^3.0.0",
"@typescript-eslint/parser": "^3.0.0",
"babel-jest": "^24.9.0",
Expand Down
2 changes: 1 addition & 1 deletion src/components/Input/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const Input: React.RefForwardingComponent<InputRef, InputProps> = (
}, [fieldName, registerField]);

return (
<Container isFocused={isFocused}>
<Container isFocused={isFocused} isErrored={!!error}>
<Icon
name={icon}
size={20}
Expand Down
8 changes: 8 additions & 0 deletions src/components/Input/styles.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import styled, { css } from 'styled-components/native';
import FeatherIcon from 'react-native-vector-icons/Feather';

interface ContainerProps {
isFocused: boolean;
isErrored: boolean;
}

export const Container = styled.View<ContainerProps>`
Expand All @@ -18,6 +20,12 @@ export const Container = styled.View<ContainerProps>`
flex-direction: row;
align-items: center;
${(props) =>
props.isErrored &&
css`
border-color: #c53030;
`}
${(props) =>
props.isFocused &&
css`
Expand Down
39 changes: 37 additions & 2 deletions src/pages/SignIn/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import {
Platform,
View,
TextInput,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/Feather';
import { ScrollView } from 'react-native-gesture-handler';
import { useNavigation } from '@react-navigation/native';
import { Form } from '@unform/mobile';
import { FormHandles } from '@unform/core';
import * as Yup from 'yup';

import getValidationErrors from '../../utils/getValidationErrors';
import Input from '../../components/Input';
import Button from '../../components/Button';

Expand All @@ -26,13 +29,45 @@ import {
CreateAccountButtonText,
} from './styles';

interface SignInFormData {
email: string;
password: string;
}

const SignIn: React.FC = () => {
const navigation = useNavigation();
const formRef = useRef<FormHandles>(null);
const passwordInputRef = useRef<TextInput>(null);

const handleSignIn = useCallback((data: object) => {
console.log(data);
const handleSignIn = useCallback(async (data: SignInFormData) => {
try {
formRef.current?.setErrors({});
const schema = Yup.object().shape({
email: Yup.string()
.required('E-mail obrigatório')
.email('Digite um e-mail válido'),
password: Yup.string().required('Senha obrigatória'),
});

await schema.validate(data, {
abortEarly: false,
});
// await signIn({
// email: data.email,
// password: data.password,
// });
// history.push('/dashboard');
} catch (err) {
if (err instanceof Yup.ValidationError) {
const errors = getValidationErrors(err);
formRef.current?.setErrors(errors);
return;
}
Alert.alert(
'Erro na autenticação',
'Ocorreu um erro ao fazer login, cheque as credenciais.',
);
}
}, []);

return (
Expand Down
53 changes: 46 additions & 7 deletions src/pages/SignUp/index.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,74 @@
import React, { useRef } from 'react';
import React, { useRef, useCallback } from 'react';
import {
Image,
KeyboardAvoidingView,
Platform,
View,
TextInput,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/Feather';
import { ScrollView } from 'react-native-gesture-handler';
import { useNavigation } from '@react-navigation/native';
import { Form } from '@unform/mobile';
import { FormHandles } from '@unform/core';
import * as Yup from 'yup';

import Input from '../../components/Input';
import Button from '../../components/Button';
import getValidationErrors from '../../utils/getValidationErrors';

import logoImg from '../../assets/logo.png';

import { Container, Title, BackToSignIn, BackToSignInText } from './styles';

interface SignUpFormData {
name: string;
email: string;
password: string;
}

const SignUp: React.FC = () => {
const navigation = useNavigation();
const formRef = useRef<FormHandles>(null);
const emailInputRef = useRef<TextInput>(null);
const passwordInputRef = useRef<TextInput>(null);

const handleSignUp = useCallback(async (data: SignUpFormData) => {
try {
formRef.current?.setErrors({});
const schema = Yup.object().shape({
name: Yup.string().required('Nome obrigatório'),
email: Yup.string()
.required('E-mail obrigatório')
.email('Digite um e-mail válido'),
password: Yup.string().min(6, 'No mínimo 6 dígitos'),
});

await schema.validate(data, { abortEarly: false });

// await api.post('/users', data);

// history.push('/');

Alert.alert(
'Cadastro realizado!',
'Você já pode fazer seu logon no GoBarber.',
);
} catch (err) {
if (err instanceof Yup.ValidationError) {
const errors = getValidationErrors(err);
formRef.current?.setErrors(errors);
return;
}

Alert.alert(
'Erro no cadastro',
'Ocorreu um erro ao fazer cadastro, tente novamente.',
);
}
}, []);

return (
<>
<KeyboardAvoidingView
Expand All @@ -41,12 +85,7 @@ const SignUp: React.FC = () => {
<View>
<Title>Crie sua conta</Title>
</View>
<Form
ref={formRef}
onSubmit={(data) => {
console.log(data);
}}
>
<Form ref={formRef} onSubmit={handleSignUp}>
<Input
autoCapitalize="words"
name="name"
Expand Down
12 changes: 12 additions & 0 deletions src/utils/getValidationErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ValidationError } from 'yup';

interface Errors {
[key: string]: string;
}
export default function getValidationErrors(err: ValidationError): Errors {
const validationErrors: Errors = {};
err.inner.forEach((error) => {
validationErrors[error.path] = error.message;
});
return validationErrors;
}
45 changes: 44 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@
core-js-pure "^3.0.0"
regenerator-runtime "^0.13.4"

"@babel/runtime@^7.0.0", "@babel/runtime@^7.4.5", "@babel/runtime@^7.6.2", "@babel/runtime@^7.8.4":
"@babel/runtime@^7.0.0", "@babel/runtime@^7.4.5", "@babel/runtime@^7.6.2", "@babel/runtime@^7.8.4", "@babel/runtime@^7.9.6":
version "7.9.6"
resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.9.6.tgz#a9102eb5cadedf3f31d08a9ecf294af7827ea29f"
integrity sha512-64AF1xY3OAkFHqOb9s4jpgk1Mm5vDZ4L3acHvAml+53nO1XbXLuDodsVpO4OIUsmemlUHMxNdYMNJmsvOwLrvQ==
Expand Down Expand Up @@ -1224,6 +1224,11 @@
dependencies:
"@types/yargs-parser" "*"

"@types/yup@^0.29.0":
version "0.29.0"
resolved "https://registry.yarnpkg.com/@types/yup/-/yup-0.29.0.tgz#0918ec503dfacb19d0b3cca0195b9f3441f46685"
integrity sha512-E9RTXPD4x44qBOvY6TjUqdkR9FNV9cACWlnAsooUInDqtLZz9M9oYXKn/w1GHNxRvyYyHuG6Bfjbg3QlK+SgXw==

"@typescript-eslint/eslint-plugin@^2.25.0":
version "2.34.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-2.34.0.tgz#6f8ce8a46c7dea4a6f1d171d2bb8fbae6dac2be9"
Expand Down Expand Up @@ -3182,6 +3187,11 @@ flatted@^2.0.0:
resolved "https://registry.yarnpkg.com/flatted/-/flatted-2.0.2.tgz#4575b21e2bcee7434aa9be662f4b7b5f9c2b5138"
integrity sha512-r5wGx7YeOwNWNlCA0wQ86zKyDLMQr+/RB8xy74M4hTphfmjlijTSSXGuH8rnvKZnfT9i+75zmd8jcKdMR4O6jA==

fn-name@~3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/fn-name/-/fn-name-3.0.0.tgz#0596707f635929634d791f452309ab41558e3c5c"
integrity sha512-eNMNr5exLoavuAMhIUVsOKF79SWd/zG104ef6sxBTSw+cZc6BXdQXDvYcGvp0VbxVVSp1XDUNoz7mg1xMtSznA==

for-in@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
Expand Down Expand Up @@ -4486,6 +4496,11 @@ locate-path@^5.0.0:
dependencies:
p-locate "^4.1.0"

lodash-es@^4.17.11:
version "4.17.15"
resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.15.tgz#21bd96839354412f23d7a10340e5eac6ee455d78"
integrity sha512-rlrc3yU3+JNOpZ9zj5pQtxnx2THmvRykwL4Xlxoa8I9lHBlVbbyPhgyPMioxVZ4NqyxaVVtaJnzsyOidQIhyyQ==

lodash.sortby@^4.7.0:
version "4.7.0"
resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438"
Expand Down Expand Up @@ -5548,6 +5563,11 @@ prop-types@^15.6.2, prop-types@^15.7.2:
object-assign "^4.1.1"
react-is "^16.8.1"

property-expr@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/property-expr/-/property-expr-2.0.2.tgz#fff2a43919135553a3bc2fdd94bdb841965b2330"
integrity sha512-bc/5ggaYZxNkFKj374aLbEDqVADdYaLcFo8XBkishUWbaAdjlphaBFns9TvRA2pUseVL/wMFmui9X3IdNDU37g==

pseudomap@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3"
Expand Down Expand Up @@ -6595,6 +6615,11 @@ symbol-tree@^3.2.2:
resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2"
integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==

synchronous-promise@^2.0.10:
version "2.0.13"
resolved "https://registry.yarnpkg.com/synchronous-promise/-/synchronous-promise-2.0.13.tgz#9d8c165ddee69c5a6542862b405bc50095926702"
integrity sha512-R9N6uDkVsghHePKh1TEqbnLddO2IY25OcsksyFp/qBe7XYd0PVbKEWxhcdMhpLzE1I6skj5l4aEZ3CRxcbArlA==

table@^5.2.3:
version "5.4.6"
resolved "https://registry.yarnpkg.com/table/-/table-5.4.6.tgz#1292d19500ce3f86053b05f0e8e7e4a3bb21079e"
Expand Down Expand Up @@ -6706,6 +6731,11 @@ toidentifier@1.0.0:
resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.0.tgz#7e1be3470f1e77948bc43d94a3c8f4d7752ba553"
integrity sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==

toposort@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/toposort/-/toposort-2.0.2.tgz#ae21768175d1559d48bef35420b2f4962f09c330"
integrity sha1-riF2gXXRVZ1IvvNUILL0li8JwzA=

tough-cookie@^2.3.3, tough-cookie@^2.3.4, tough-cookie@~2.5.0:
version "2.5.0"
resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.5.0.tgz#cd9fb2a0aa1d5a12b473bd9fb96fa3dcff65ade2"
Expand Down Expand Up @@ -7232,3 +7262,16 @@ yargs@^14.2.0:
which-module "^2.0.0"
y18n "^4.0.0"
yargs-parser "^15.0.1"

yup@^0.29.0:
version "0.29.0"
resolved "https://registry.yarnpkg.com/yup/-/yup-0.29.0.tgz#c0670897b2ebcea42ebde12b3567f55ea3a7acaf"
integrity sha512-rXPkxhMIVPsQ6jZXPRcO+nc+AIT+BBo3012pmiEos2RSrPxAq1LyspZyK7l14ahcXuiKQnEHI0H5bptI47v5Tw==
dependencies:
"@babel/runtime" "^7.9.6"
fn-name "~3.0.0"
lodash "^4.17.15"
lodash-es "^4.17.11"
property-expr "^2.0.2"
synchronous-promise "^2.0.10"
toposort "^2.0.2"

0 comments on commit ec17e55

Please sign in to comment.