React Native Build & Validate Forms with Formik & Yup
To make you understand easy form-building in react native, I will create a straightforward form with name, email, and password input fields.
From a database’s perspective, a form is a window or screen that includes various fields, or spaces to insert data. Every field contains a field label so that any user who can view the form gets an idea of its contents.
In software development, a form is used to get the values from a user and store that user entered information in the database by making the API calls.
In React Native, working with form’s input controls and validation is slightly tricky. This is where Formik and Yup come in; Formik enables you to build forms faster, whereas Yup takes care of validation.
Table of Contents
Prerequisite
To build forms and validation in React Native, we must have following tools, frameworks, and packages.
- NPM
- Node
- React-Native
- React-Native CLI
- Formik
- Yup
- IDE or Text Editor
- Xcode for iOS
- Android Studio
Create React Native Project
Install latest React Native CLI on your device.
npm install -g react-native-cli
By running the following command, install a new React Native app.
react-native init rnFormsFormikYup
Enter in the project directory using the given command.
cd rnFormsFormikYup
Install Formik Package & Yup Packages
In this step we will install Formik and Yup packages to create and validate forms in React Native.
# for npm
npm install formik yup --save
# for yarn
yarn add formik yup
Formik is a light-weight and powerful library that assists you with the 3 most disturbing parts of form building in react-native. It also helps in keeping things organized by building, testing, and refactoring your forms.
- Handling form submission
- Validation and error messages
- Managing form values of form state
Yup is a JavaScript schema builder for value parsing and validation. Assign a schema, convert a value to match, validate the shape of an existing value, or both.
Yup schema are incredibly powerful and support modeling complex, interdependent validations, or value transformations.
Build Form in React Native with Formik
Now, we are going to create a basic form using the Formik component. Open your App.js file and import the formik package at the top part of the app file.
import { Formik } from 'formik'
Next, replace the following code with your existing code in the same file.
// App.js
import React, { Component } from 'react';
import { TextInput, Text, Button, Alert, View, StyleSheet } from 'react-native';
import { Formik } from 'formik'
export default class App extends Component {
render() {
const inputStyle = {
borderWidth: 1,
borderColor: '#4e4e4e',
padding: 12,
marginBottom: 5,
};
return (
<Formik
initialValues={{
name: '',
email: '',
password: ''
}}
onSubmit={values => Alert.alert(JSON.stringify(values))}
>
{({ values, handleChange, errors, setFieldTouched, touched, isValid, handleSubmit }) => (
<View style={styles.formContainer}>
<TextInput
value={values.name}
style={inputStyle}
onChangeText={handleChange('name')}
onBlur={() => setFieldTouched('name')}
placeholder="Name"
/>
{touched.name && errors.name &&
<Text style={{ fontSize: 12, color: '#FF0D10' }}>{errors.name}</Text>
}
<TextInput
value={values.email}
style={inputStyle}
onChangeText={handleChange('email')}
onBlur={() => setFieldTouched('email')}
placeholder="E-mail"
/>
{touched.email && errors.email &&
<Text style={{ fontSize: 12, color: '#FF0D10' }}>{errors.email}</Text>
}
<TextInput
value={values.password}
style={inputStyle}
onChangeText={handleChange('password')}
placeholder="Password"
onBlur={() => setFieldTouched('password')}
secureTextEntry={true}
/>
{touched.password && errors.password &&
<Text style={{ fontSize: 12, color: '#FF0D10' }}>{errors.password}</Text>
}
<Button
color="#3740FE"
title='Submit'
disabled={!isValid}
onPress={handleSubmit}
/>
</View>
)}
</Formik>
);
}
}
const styles = StyleSheet.create({
formContainer: {
padding: 50
}
});
console.disableYellowBox = true;
We defined the initialValues with the help of the Formik tag to set the form’s initial state.
Formik controls the inputs control with the handleChange() event.
We also kept the button disabled when the form fields are invalid.
Here is the output for the React Native form.
React Native Form Validation with Yup
We have already installed Yup now. In this step, we will learn to validate form input controls using the Yup package.
<Formik
initialValues={{
name: '',
email: '',
password: ''
}}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={yup.object().shape({
name: yup
.string()
.required('Please, provide your name!'),
email: yup
.string()
.email()
.required(),
password: yup
.string()
.min(4)
.max(10, 'Password should not excced 10 chars.')
.required(),
})}
>
Setting up validationSchema property in the Formik is easy. The schema allows input controls to validate quickly.
We can quickly validate email input control even you can set the custom messages with it.
Validating and managing various input Field types is also easy with Yup.
You can check out all the form validation options here.
Here is the final code that we have placed in the App.js file.
// App.js
import React, { Component } from 'react';
import { TextInput, Text, Button, Alert, View, StyleSheet } from 'react-native';
import * as yup from 'yup'
import { Formik } from 'formik'
export default class App extends Component {
render() {
const inputStyle = {
borderWidth: 1,
borderColor: '#4e4e4e',
padding: 12,
marginBottom: 5,
};
return (
<Formik
initialValues={{
name: '',
email: '',
password: ''
}}
onSubmit={values => Alert.alert(JSON.stringify(values))}
validationSchema={yup.object().shape({
name: yup
.string()
.required('Please, provide your name!'),
email: yup
.string()
.email()
.required(),
password: yup
.string()
.min(4)
.max(10, 'Password should not excced 10 chars.')
.required(),
})}
>
{({ values, handleChange, errors, setFieldTouched, touched, isValid, handleSubmit }) => (
<View style={styles.formContainer}>
<TextInput
value={values.name}
style={inputStyle}
onChangeText={handleChange('name')}
onBlur={() => setFieldTouched('name')}
placeholder="Name"
/>
{touched.name && errors.name &&
<Text style={{ fontSize: 12, color: '#FF0D10' }}>{errors.name}</Text>
}
<TextInput
value={values.email}
style={inputStyle}
onChangeText={handleChange('email')}
onBlur={() => setFieldTouched('email')}
placeholder="E-mail"
/>
{touched.email && errors.email &&
<Text style={{ fontSize: 12, color: '#FF0D10' }}>{errors.email}</Text>
}
<TextInput
value={values.password}
style={inputStyle}
onChangeText={handleChange('password')}
placeholder="Password"
onBlur={() => setFieldTouched('password')}
secureTextEntry={true}
/>
{touched.password && errors.password &&
<Text style={{ fontSize: 12, color: '#FF0D10' }}>{errors.password}</Text>
}
<Button
color="#3740FE"
title='Submit'
disabled={!isValid}
onPress={handleSubmit}
/>
</View>
)}
</Formik>
);
}
}
const styles = StyleSheet.create({
formContainer: {
padding: 50
}
});
console.disableYellowBox = true;
Here is the final result.
Conclusion
We have completed the React Native Forms tutorial, and In this tutorial, we have learned how to create Build & Validate Forms using Formik & Yup package.
I hope you liked this tutorial. Please share it with others.
You can get the complete code of this tutorial on this Github repository.