React Native form validations with Formik and Yup
October 27, 2020
A Form is a screen section which allows users to interact with and send controlled/validated informations to a server.
yarn add formik
yarn add yup
The finished Log In screen should look like this:
import * as yup from 'yup'
import { Formik } from 'formik'
import React, { Fragment } from 'react';
import { SafeAreaView,Button, TextInput,Text,Alert} from 'react-native';
const Login = () => {
return <SafeAreaView
style={{
flex:1
}}
>
<Formik
initialValues={{ email: '', password: '' }}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={yup.object().shape({
email: yup
.string()
.email()
.required(),
password: yup
.string()
.matches(
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
"Must Contain 8 Characters, One Uppercase, One Lowercase, One Number and one special case Character"
)
.required(),
})}
>
{({ values, handleChange, errors, setFieldTouched, touched, isValid, handleSubmit }) => (
<Fragment>
<TextInput
style={{margin:10,borderBottomWidth : 1.0,padding:10}}
value={values.email}
onChangeText={handleChange('email')}
onBlur={() => setFieldTouched('email')}
placeholder="E-mail"
/>
{touched.email && errors.email &&
<Text style={{ fontSize: 10, color: 'red',paddingHorizontal:10}}>{errors.email}</Text>
}
<TextInput
style={{margin:10,borderBottomWidth : 1.0,padding:10}}
value={values.password}
onChangeText={handleChange('password')}
placeholder="Password"
onBlur={() => setFieldTouched('password')}
secureTextEntry={true}
/>
{touched.password && errors.password &&
<Text style={{ fontSize: 10, color: 'red',paddingHorizontal:10}}>{errors.password}</Text>
}
<Button
title='Sign In'
disabled={!isValid}
onPress={handleSubmit}
/>
</Fragment>
)}
</Formik>
</SafeAreaView>
}
export default Login;