Table of contents
1.
Introduction
2.
Introduction to React Native Components
3.
Key React Native Components
4.
Example of a simple React Native component:
5.
Introducing Yup & Formik
6.
How to Add Validation to a Form
7.
React Native State
7.1.
Managing State in React Native:
7.2.
Example of using useState for form validation in React Native:
8.
Expo CLI
8.1.
How to Set Up Expo CLI:
9.
Example of Validating a Form Using React Native and Expo
10.
Frequently Asked Questions
10.1.
What is React Native used for?
10.2.
How do you handle state in React Native?
10.3.
What is Expo CLI and why should I use it?
11.
Conclusion
Last Updated: Jan 3, 2025
Easy

React Native Validation

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

React Native is a popular open-source framework used to build mobile applications for both Android and iOS. Validation is a critical aspect of mobile app development, ensuring that user inputs are accurate, secure, and consistent. In React Native, implementing validation is essential for creating a seamless and error-free user experience. Whether it's validating login credentials, form data, or user-generated content, React Native offers flexible solutions to handle validation efficiently. With built-in libraries and third-party tools, developers can implement real-time and server-side validation to meet various requirements.

React Native Validation

In this article, we'll discuss how React Native can be used for form validation, a crucial feature for ensuring that users input data correctly in mobile apps. 

Introduction to React Native Components

React Native components are the building blocks of any React Native application. A component is a JavaScript function or class that returns a piece of UI. Components can be either functional or class-based, and they control how the user interface of the app behaves and appears.

Key React Native Components

  1. View: This is a container that supports layout with flexbox, style, and touch handling.
     
  2. Text: Used to display text on the screen.
     
  3. TextInput: This component is essential for collecting user input, such as in forms.
     
  4. Button: Used to trigger actions, like submitting a form or navigating to another screen.

Example of a simple React Native component:

import React from 'react';
import { View, Text, TextInput, Button } from 'react-native';
const MyComponent = () => {
  return (
    <View>
      <Text>Hello, React Native!</Text>
      <TextInput
        placeholder="Enter your name"
        style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
      />
      <Button title="Submit" onPress={() => alert('Button pressed')} />
    </View>
  );
};


export default MyComponent;


Explanation: This simple component shows a greeting message, a text input field where the user can type their name, and a button that displays an alert when pressed.

Introducing Yup & Formik

Yup is a JavaScript schema builder for value parsing & validation. It allows you to define a schema for your form data, specifying rules like required fields, min/max values, string formats & more. Yup schemas are very readable & expressive.

Formik is a small library that helps you deal with forms in React. It manages form state, validation, & submission. Formik works well with Yup for validation.

To use Yup & Formik in your React Native project, first install them via npm:

npm install formik yup


Now you can import them in your form component file:

import { Formik } from 'formik';
import * as Yup from 'yup';


With Yup & Formik in place, you're ready to start building a form with validation. Formik will handle the form state & submission, while Yup will define the validation rules.

How to Add Validation to a Form

To add validation to a form with Formik & Yup:

1. Define your form's initial values
 

2. Create a validation schema with Yup  
 

3. Render the form with Formik
 

4. Display error messages
 

For example:

// Initial form values
const initialValues = {
  email: '',
  password: '',
};


// Validation schema
const validationSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
  password: Yup.string().min(6, 'Too short').required('Required'),
});


function LoginForm() {
  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={values => console.log(values)}
    >
      {({ handleChange, handleBlur, handleSubmit, values, errors, touched }) => (
        <View>
          <TextInput 
            onChangeText={handleChange('email')}
            onBlur={handleBlur('email')}
            value={values.email}
          />
          {touched.email && errors.email &&
            <Text>{errors.email}</Text>
          }
          
          <TextInput 
            onChangeText={handleChange('password')}
            onBlur={handleBlur('password')}
            value={values.password}
            secureTextEntry
          />
          {touched.password && errors.password &&
            <Text>{errors.password}</Text>
          }
        
          <Button onPress={handleSubmit} title="Submit" />
        </View>
      )}
    </Formik>
  );
}


In this example:

  • We define the form's initialValues 
     
  • Create a validationSchema with Yup rules
     
  • Render the form using Formik's component & props
     
  • Display error messages when fields are touched & have errors
     

Formik provides props like handleChange, handleBlur, values, errors & touched to manage the form state & validation.

With this basic setup, the form will display errors if the user enters an invalid email address or password less than 6 characters. You can customize the validation rules & error messages as needed.

React Native State

State in React Native refers to the data that controls the behavior of a component. When the state of a component changes, React Native automatically re-renders the component to reflect the updated data. State is commonly used to manage dynamic data such as user inputs, form values, or UI changes.

Managing State in React Native:

React provides a useState hook (for functional components) and this.setState() (for class components) to manage state.

Example of using useState for form validation in React Native:

import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
const FormValidation = () => {
  const [name, setName] = useState('');
  const [errorMessage, setErrorMessage] = useState('');


  const handleSubmit = () => {
    if (!name) {
      setErrorMessage('Name cannot be empty');
    } else {
      setErrorMessage('');
      alert('Form Submitted');
    }
  };


  return (
    <View>
      <TextInput
        placeholder="Enter your name"
        value={name}
        onChangeText={(text) => setName(text)}
        style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
      />
      {errorMessage ? <Text style={{ color: 'red' }}>{errorMessage}</Text> : null}
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
};


export default FormValidation;

 

Explanation:

  • useState: We define two state variables: name to hold the input value and errorMessage to hold the validation error message.
     
  • Form Validation: When the user presses the "Submit" button, the handleSubmit function checks if the name is empty. If it is, an error message is displayed; otherwise, the form is submitted.

Expo CLI

Expo is a toolchain built around React Native that simplifies the development process. It provides a set of libraries and services that make it easy to build, test, and deploy React Native applications. One of the key advantages of using Expo is that it eliminates the need for setting up a complex development environment, which can be challenging for beginners.

How to Set Up Expo CLI:

1.Install Node.js: Make sure you have Node.js installed on your computer. You can download it from here.
 

2.Install Expo CLI: Run the following command to install Expo CLI globally:

npm install -g expo-cli

 

3.Create a New Project: To start a new React Native project, run:

expo init my-new-project
Select a template (e.g., "blank") and follow the prompts.

 

4.Run the Project: To run the project on your emulator or physical device, navigate to your project directory and run:

expo start


Expo provides a QR code in the terminal that you can scan with the Expo Go app (available on both Android and iOS). This allows you to see your app running in real-time without needing to configure a full React Native environment.

Example of Validating a Form Using React Native and Expo

Now, let’s combine React Native and Expo to create a form that validates user input.

Step-by-Step Example:

import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';

const App = () => {
  const [email, setEmail] = useState('');
  const [emailError, setEmailError] = useState('');


  const validateEmail = (email) => {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
  };

  const handleSubmit = () => {
    if (!email) {
      setEmailError('Email is required');
    } else if (!validateEmail(email)) {
      setEmailError('Please enter a valid email');
    } else {
      setEmailError('');
      alert('Form Submitted Successfully');
    }
  };

  return (
    <View>
      <TextInput
        placeholder="Enter your email"
        value={email}
        onChangeText={(text) => setEmail(text)}
        style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
      />
      {emailError ? <Text style={{ color: 'red' }}>{emailError}</Text> : null}
      <Button title="Submit" onPress={handleSubmit} />
    </View>
  );
};
export default App;


Explanation:

  • Email Validation: This example checks if the email input is valid using a regular expression. If the email is invalid, it shows an error message.
     
  • Expo Integration: Since we used Expo to create and run this project, we can quickly test it on a physical device by scanning the QR code.

Frequently Asked Questions

What is React Native used for?

React Native is a framework that allows developers to build mobile applications for Android and iOS using JavaScript and React.

How do you handle state in React Native?

State in React Native is managed using the useState hook in functional components or this.setState() in class components. It helps manage dynamic data such as user inputs and form values.

What is Expo CLI and why should I use it?

Expo CLI is a tool that simplifies the development and deployment of React Native applications. It eliminates the need to set up a native development environment, making it ideal for beginners.

Conclusion

In this article, we discussed React Native, focusing on form validation, state management, and how to use Expo CLI for building and running mobile applications. By now, you should have a solid understanding of how to create a basic form with validation and handle user input efficiently in React Native. We also discussed Expo CLI, a powerful tool for simplifying the development process. 

You can also check out our other blogs on Code360.

Live masterclass