React Native Form Validation with Formik and Yup Tutorial

This quick React Native form validation tutorial will help you understand how to create a basic form in react native application. How to validate form values using the Formik and Yup packages in React native application from scratch.

In this guide, you will see how to build a form in react native mobile application, this form will have a simple name, email, mobile, and password fields.

We will add the required value, minimum, maximum characters, number, and string validation in the react-native form.

Formik is an intuitive JavaScript library best used for React and React Native components. The hooks pattern solves the three major problems: getting values on and off concerning form state and implementing validation, and showing validation error messages in React native app.

Yup is a JavaScript-based schema builder for value parsing and validation. You can use it to transform a value or validate the current value. It offers utterly significant ways for the schema that allow modeling complex, interdependent validations or value transformations.

How to Validate Form in React Native using Yup and Formik

  • Step 1: Install React Native CLI
  • Step 2: Create New React Native App
  • Step 3: Install Yup and Formik Packages
  • Step 4: Create Form Component
  • Step 5: Register Form Component in App Js
  • Step 6: Test Application

Install React Native CLI

You must install Node 12 LTS or higher version in your system; you may use either npm or yarn to begin installing the Expo CLI.

# npm
npm install -g expo-cli

# yarn
yarn global add expo-cli

Create New React Native App

In this step, you have to execute provided command to download the fresh React Native application.

expo init RnBlogProject

Then, move into the app directory.

cd RnBlogProject

Install Yup and Formik Packages

In this step, you need to install the formik and yup packages package in react native application with the help of the following command.

# npm
npm install formik yup

# yarn
yarn add formik yup

Create Form Component

In this step, you have to create a form_component.js file inside the reactive native project directory.

To create the form in react native, we have to import the Formik from ‘formik’ package, and * as yup from ‘yup’ package.

To create the input elements of form you require to import StyleSheet, Text, TextInput, Alert, Button, and View from ‘react-native’ module.

Now, update code in form_component.js file.

import React, { Component } from 'react';

import { StyleSheet, Text, TextInput, Alert, Button, View } from 'react-native';
import { Formik } from 'formik'
import * as yup from 'yup'


export default class FormComponenet extends Component {
  render() {
    const customCss = {
      borderWidth: 1,
      padding: 10,
      marginBottom: 12,
      borderColor: '#cccccc',
    };

    return (
      <Formik
        initialValues={{ 
          name: '',
          email: '', 
          mobile: '',
          password: '' 
        }}
        onSubmit={values => Alert.alert(JSON.stringify(values))}
        validationSchema={yup.object().shape({
          name: yup
            .string()
            .required('Name is required.'),
          email: yup
            .string()
            .email()
            .required('Email is required.'),
          mobile: yup
            .number()
            .max(10)
            .required(),            
          password: yup
            .string()
            .min(3, 'Password can not be less than 3 characters.')
            .max(11, 'Password can not be more than 12 characters long.')
            .required(),
        })}
       >
        {({ values, errors, setFieldTouched, touched, handleChange, isValid, handleSubmit }) => (
          <View style={styles.mainWrapper}>
            <TextInput
              value={values.name}
              style={customCss}
              onBlur={() => setFieldTouched('name')}
              onChangeText={handleChange('name')}
              placeholder="Name"
            />
            {touched.name && errors.name &&
              <Text style={{ fontSize: 11, color: 'red' }}>{errors.name}</Text>
            }            
            <TextInput
              value={values.email}
              style={customCss}
              onBlur={() => setFieldTouched('email')}
              onChangeText={handleChange('email')}
              placeholder="E-mail"
            />
            {touched.email && errors.email &&
              <Text style={{ fontSize: 11, color: 'red' }}>{errors.email}</Text>
            }
            <TextInput
              value={values.mobile}
              style={customCss}
              placeholder="Mobile"
              onBlur={() => setFieldTouched('mobile')}
              onChangeText={handleChange('mobile')}
            />
            {touched.mobile && errors.mobile &&
              <Text style={{ fontSize: 11, color: 'red' }}>{errors.mobile}</Text>
            }            
            <TextInput
              value={values.password}
              style={customCss}
              placeholder="Password"
              onBlur={() => setFieldTouched('password')}
              onChangeText={handleChange('password')}
              secureTextEntry={true}
            />
            {touched.password && errors.password &&
              <Text style={{ fontSize: 11, color: 'red' }}>{errors.password}</Text>
            }
            <Button
              color="blue"
              title='Sa ve'
              disabled={!isValid}
              onPress={handleSubmit}
            />
          </View>
        )}
      </Formik>
    );
  }

}

const styles = StyleSheet.create({
  mainWrapper: {
    padding: 40 
  }
});

Register Form Component in App Js

In this step, you have to register the form component in the primary app js file.

Open the App.js file; and add the form component as given below.


import React from 'react';
import FormComponenet from './form_component.js'


export default function App() {
  return (
    <FormComponenet/>
  );
}

Test Application

Now, you have to execute command to initiate the react native development server;

You may use any of the given below command based on your package manager.

# npm
npm start


# yarn
yarn start

For testing the form and form validation you may download Expo app on your device and test the app on your mobile device.

After starting the app, you have to scan the QR code through your app, app will start on your device.

React Native Form Validation with Formik and Yup Tutorial

Summary

This quick guide has taught us how to integrate form validation in React native applications using the third-party Formik and Yup packages. We showed you how to display error messages when the form validation doesn’t meet the validation requirement.