Handle different field types in React Native forms with formik and yup

Published on Oct 26, 2019

7 min read

EXPO

In the previous post, you did a lot of things. From creating Login and Signup forms from scratch and using powerful libraries like Formik and yup to validate those forms.

In this tutorial, let us extend our knowledge of building and validating forms by handling different input field types other than strings. You are also going to take a look at my share of the solution on how to gracefully create a Confirm Password field and validate it using the reference of already setup password field.

Lastly, there is a small bonus section that will allow you to complete the UI of the form. You are going to add a toggle icon to show or hide the password for the user to re-check.

This tutorial is going to use an already setup source code from this Github repo release.

After installing the source code, please navigate inside the project directory and install dependencies by running the following command:

npm install
# or
yarn install

Table of Contents

🔗
  • Requirements
  • Adding Confirm Password Field to Signup Screen
  • Handling a CheckBox with Formik and Yup
  • Bonus: Hide/Show Password fields
  • Conclusion

Requirements

🔗

To follow this tutorial, please make sure you following installed on your local development environment and access to the services mentioned below.

  • Nodejs (>= 10.x.x) with npm/yarn installed
  • expo-cli (>= 3.x.x), (previously known as create-react-native-app)

Adding Confirm Password Field to Signup Screen

🔗

In the [last post](LINK HERE), I left you with a challenge to figure out how to add validation for confirm password field in the signup screen using yup. If you succeeded, please skip this section and move on the next one. If you are still curious about it, open Signup.js file and a new input field for the confirm password as well as a new property with the same name in the initialValues object of Formik element.

1<Formik
2 initialValues={{
3 name: '',
4 email: '',
5 password: '',
6 // add this
7 confirmPassword: ''
8 }}
9 onSubmit={values => {
10 this.handleSubmit(values);
11 }}
12 validationSchema={validationSchema}
13>
14 {({
15 handleChange,
16 values,
17 handleSubmit,
18 errors,
19 isValid,
20 touched,
21 handleBlur,
22 isSubmitting
23 }) => (
24 <Fragment>
25 {/* Rest of the code remains same */}
26 <FormInput
27 name="password"
28 value={values.confirmPassword}
29 onChangeText={handleChange('confirmPassword')}
30 placeholder="Confirm password"
31 secureTextEntry
32 iconName="ios-lock"
33 iconColor="#2C384A"
34 onBlur={handleBlur('confirmPassword')}
35 />
36 <ErrorMessage
37 errorValue={touched.confirmPassword && errors.confirmPassword}
38 />
39 <View style={styles.buttonContainer}>
40 <FormButton
41 buttonType="outline"
42 onPress={handleSubmit}
43 title="SIGNUP"
44 buttonColor="#F57C00"
45 disabled={!isValid || isSubmitting}
46 loading={isSubmitting}
47 />
48 </View>
49 </Fragment>
50 )}
51</Formik>

In the validationSchema object add a new property called confirmPassword that is going to be a string. Next, using oneOf the method from Yup's API. Inside its array parameter, it accepts a Yup.ref() which creates a reference to another sibling from the intialValues object.

1const validationSchema = Yup.object().shape({
2 name: Yup.string()
3 .label('Name')
4 .required()
5 .min(2, 'Must have at least 2 characters'),
6 email: Yup.string()
7 .label('Email')
8 .email('Enter a valid email')
9 .required('Please enter a registered email'),
10 password: Yup.string()
11 .label('Password')
12 .required()
13 .min(4, 'Password must have more than 4 characters '),
14
15 // add this
16 confirmPassword: Yup.string()
17 .oneOf([Yup.ref('password')], 'Confirm Password must matched Password')
18 .required('Confirm Password is required')
19});

The Yup.ref('password') here refers to the actual password field. Let us try to add a different password to both of these fields and see what happens.

I am going to add pass to the password field (since it accepts four minimum characters) and passo to the confirmPassword field.

1

See the error message being displayed when both input fields do not match.

Handling a CheckBox with Formik and Yup

🔗

You can create and validate other field types using Formik and Yup. In this section, you are going to achieve that by creating a checkbox field that is quite common when signing up into new applications where they make you agree to all of their terms and app policies.

Open Signup.js file and the following checkbox element from react-native-elements library. It is going to contain a boolean value. In the initialValues object, please add that.

1// import checkbox element
2import { Button, CheckBox } from 'react-native-elements'
3
4initialValues={{
5 name: '',
6 email: '',
7 password: '',
8 confirmPassword: '',
9 // add "check" to initial values
10 check: false
11}}

At the checkbox, there is a prop called checked that is required. It holds the current value of the element whether it checked or not. After you have defined the confirmPassword input field, please state the following.

1<CheckBox
2 containerStyle={styles.checkBoxContainer}
3 checkedIcon="check-box"
4 iconType="material"
5 uncheckedIcon="check-box-outline-blank"
6 title="Agree to terms and conditions"
7 checkedTitle="You agreed to our terms and conditions"
8 checked={values.check}
9 onPress={() => setFieldValue('check', !values.check)}
10/>

The required prop checked that changes the icon to check or uncheck. By default, it will be marked uncheck. The uncheckedIcon prop takes the value of an icon. The title prop's value of the checkbox when marked check, changes to the value of checkedTitle. These are fair advantages of using a component library like react-native-elements.

Using setFieldValue from Formik props, you can set the value of the check to true or false. It accepts the reference of the key check itself as the first parameter. !values.check states the opposite of the current value of the key check.

Lastly, edit the validationSchema by adding the key check. It is going to use boolean schema type.

1check: Yup.boolean().oneOf([true], 'Please check the agreement');

See the below demonstration on how it works.

2

Bonus: Hide/Show Password fields

🔗

In this section, you are going to add the ability to hide or show the password on the corresponding field. By the end of this section, the password input field is going to look like this.

To start, open Login.js file and import TouchableOpacity from react-native and Ionicons from expo's vector icons library which comes with Expo SDK.

1import { StyleSheet, SafeAreaView, View, TouchableOpacity } from 'react-native';
2import { Ionicons } from '@expo/vector-icons';

Next step is to define an initial state inside the Login component. This will help track of the current icon being shown and the visibility of the password.

1state = {
2 passwordVisibility: true,
3 rightIcon: 'ios-eye'
4};

The define a handler method that will trigger on the onPress prop of TouchableOpacity. It checks the previous state of the icon and the password's visibility field.

1handlePasswordVisibility = () => {
2 this.setState(prevState => ({
3 rightIcon: prevState.rightIcon === 'ios-eye' ? 'ios-eye-off' : 'ios-eye',
4 passwordVisibility: !prevState.passwordVisibility
5 }));
6};

Then go to the password input field and add the prop rightIcon from react-native-elements, you are going to pass the TouchableOpacty for the icon to be touchable and trigger some function (in this case, handlePasswordVisibility).

Also, tame the prop secureEntryText. It accepts a boolean as its value, and that is what passwordVisibility is. If its value is true, which is the initial state, it will secure the password field entry. When clicked on the icon, the visibility is going to change to false, and then the password will be shown.

1secureTextEntry={passwordVisibility}
2rightIcon={
3 <TouchableOpacity onPress={this.handlePasswordVisibility}>
4 <Ionicons name={rightIcon} size={28} color='grey' />
5 </TouchableOpacity>
6}

This is the output you are going to get.

Conclusion

🔗

That's it. This post and the previous one covers enough to get you started and create forms in advance forms in React Native apps using formik and yup.

You can go ahead and add the toggle password visibility to the Signup form screen as well. You will find the source code from this Github repo release.

Originally published at Heartbeat


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.