Validating data provided by the user is an essential step in any React Native application to make sure that the information on the application is complete and accurate. This way, we can avoid potential errors due to corrupt data.
One application of data validation is making sure that a user enters a valid email and password when signing up on a React Native application so that they don’t have problems later on when logging in. We’ll go over how to implement data validation with Yup on a React Native application with a dummy sign-up page running on Expo.
First of all, if we don't have it already, we need to install the yup
dependency on our system, as follows:
npm install yup
Note: You do not have to install anything in the code executable below, as all such dependencies have already been installed for you.
Once, we’ve installed the yup
dependencies, we can now import it and other required dependencies into our React Native application, as follows:
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';import React, { useState } from 'react';import * as Yup from 'yup';
Note the import statement for Yup on line 3.
Our signup will have three key inputs: the user’s email, the user’s password, and a second input of the password to make sure the user entered the correct password (since the entered password is hidden on the screen).
Let’s define a validation schema for the three user inputs using Yup. Here’s the validation schema we’ve used:
const signUpSchema = Yup.object().shape({email: Yup.string().email('Email is Invalid').required('Email Cannot Be Empty'),password: Yup.string().min(10, 'Password Must have a Minimum if ten Characters').required('Password Cannot Be Empty'),confirmPassword: Yup.string().oneOf([Yup.ref('password'), null], 'Passwords must match').required('Please Enter Password Again!'),});
Here’s a brief explanation of the code snippet above:
Line 1: We use the object
and shape
methods to define the schema having three fields: email
, password
, and confirmPassword
.
Line 2: We define the email
field as a string schema using the string
method. We then chain the email
and required
validation methods onto it in order for Yup to validate if the email is provided and follows the correct email format.
Line 3: We define the password
field as a string schema using the string
method. We then chain the min
and required
validation methods onto it in order for Yup to validate if the password is provided and if it is of at least ten characters.
Line 4: We define the confirmPassword
field as a string schema using the string
method. We then chain the oneOf
and required
validation methods onto it in order for Yup to validate if the password is provided and if it matches the previously provided password.
We declare the signUpScreen
component that makes up our sign-up page as follows:
export default function signUpScreen() {
We’ll use the following state variables in the React Native application to make it more dynamic:
const [email, setEmail] = useState('');const [password, setPassword] = useState('');const [confirmPassword, setConfirmPassword] = useState('');const [success, setSuccess] = useState(false);const [errors, setErrors] = useState({});
The email, password, and confirmPassword state variables keep track of the user inputs. The success state variable keeps track of whether the sign-up process was a success, and the errors state variable keeps track of all the current validation errors.
The following method defines the logic of how to handle the sign-up process. Notice that the very first step is validating the user credentials on line 2.
const signUp = async () => {try {// Awaiting for Yup to validate textawait signUpSchema.validate({ email, password, confirmPassword }, { abortEarly: false });// Reseting Warnings and displaying success message if all goes wellsetErrors({});setSuccess(true);} catch (error) {// Reseting Succes MessagesetSuccess(false);// Setting error messages identified by Yupif (error instanceof Yup.ValidationError) {// Extracting Yup specific validation errors from list of total errorsconst yupErrors = {};error.inner.forEach((innerError) => {yupErrors[innerError.path] = innerError.message;});// Saving extracted errorssetErrors(yupErrors);}}};
The following JSX html defines the rendering logic of the sign-up page:
<View style={styles.centered}><Text style={styles.textTitle}>Email</Text><TextInput style={styles.inputBox} placeholder="Email" value={email} onChangeText={setEmail} />{errors.email && <Text style={styles.textWarning}>{errors.email}</Text>}<Text style={styles.textTitle}>Password</Text><TextInput style={styles.inputBox} placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry />{errors.password && <Text style={styles.textWarning}>{errors.password}</Text>}<Text style={styles.textTitle}>Confirm Password</Text><TextInput style={styles.inputBox} placeholder="Confirm Password" value={confirmPassword} onChangeText={setConfirmPassword} secureTextEntry />{errors.confirmPassword && <Text style={styles.textWarning}>{errors.confirmPassword}</Text>}<div style={{padding: 10}} /><Button title="SIGN UP" onPress={signUp} />{success && <Text style={styles.textSuccess}>Success!</Text>}</View>
Here’s the complete application you can use to test out and play around with the data validation logic we’ve implemented for the sign-up process. Simply click the “Run” button to execute the code. You need to wait a while for the code to compile. After that, you can click on the link in front of “Your app can be found at:” to open the React Native application.
module.exports = function(api) { api.cache(true); return { presets: ['babel-preset-expo'], }; };
Free Resources