How to install yup in react native in JavaScript?


The Yup is an NPM package we can install in the react-native application. It is used to validate the form values stored in a single object. Also, we can add different kinds of validations to the different form fields using the Yup.

Users can execute the below command in the project directory to install the Yup in react native.

npm i Yup

Users can use the below command if they are using the Yarn.

yarn i Yup

Syntax

Users can follow the syntax below to use the Yup for the form validation in the react-native application.

const schema = Yup.object().shape({
   key1: Yup.string().required("Required"),
});
await schema.validate(values);

In the above syntax, we have created the schema using the Yup and used the validate() method to validate values according to the rules defined in the schema. Here, values are an object containing form property names and value pairs.

Steps

  • Step 1 − First, developers require to import the required things from the Yup.

  • Step 2 − In the App() component, create a ‘userFormSchema’ using the Yup, which defines rules for the student_id, age, and portfolio fields. Here, student_id is a string and required field, age is a positive integer and required field, and portfolio is the URL of the website.

  • Step 3 − Now, define the states for the student info and validation message using the ‘useState’ hooks.

  • Step 4 − Define the handleChange() function, which takes the key and value as a parameter, and updates the value in the ‘initialValue’ state object.

  • Step 5 − Next, define the validateValues() function, which uses the validate() method by taking the userFormSchema as a reference and the studentInfo object as a parameter to validate the form values.

  • Step 6 − Set the message to the ‘message’ state according to the validation of form values.

Example 1

In the example below, we have created a form to collect student information. We have added three input fields to take the student_id, age, and portfolio website’s URL. Also, we have created the submit button.

Whenever the user clicks the submit button, it invokes the validateValues() function, which shows the validation message on the screen.

import React, { useState } from "react";
import * as Yup from "yup";
import { TouchableOpacity, View, TextInput, Text, Button } from "react-native";
const App = () => {
   // creating the user form schema using Yup to validate student_id, age, and portfolio
   const userFormSchema = Yup.object().shape({
   student_id: Yup.string().required("Required"),
   age: Yup.number().required("Required").positive().integer(),
   portfolio: Yup.string().url().nullable(),
   });
   const [studentInfo, setStudentInfo] = useState({
      student_id: "",
      age: 13,
      portfolio: "",
   });
   const [message, setMessage] = useState("");

   function handleChange(key, val) {
      setStudentInfo({ ...studentInfo, [key]: val });
   }
   // creating the handleFormSubmit function to handle the form submission
   async function validateValues() {
      try {
         await userFormSchema.validate(studentInfo);
         setMessage("Form is successfully submitted with no errors!");
      } catch (error) {
         console.log(error);
         setMessage("Form is not submitted due to errors!");
      }
   }
   return (
      // rendering the form
      <View style = {{ width: "70%" }}>
         {/* text inputs */}
         <TextInput
            placeholder = "student_id"
            value = {studentInfo.student_id}
            onChangeText = {(value) => handleChange("student_id", value)}
         />
         <TextInput
            placeholder = "age"
            value = {studentInfo.age}
            onChangeText = {(value) => handleChange("age", value)}
         />

         <TextInput
            placeholder = "portfolio"
            value = {studentInfo.portfolio}
            onChangeText = {(value) => handleChange("portfolio", value)}
         />
         {/* submit button */}
         <TouchableOpacity onPress = {validateValues}>
            <Text> Submit Form </Text>
         </TouchableOpacity>
         <Text> {message} </Text>
      </View>
   );
};
export default App;

Output

Example 2

The below example is the advanced version of the above example. Here, we have three input fields that take the users' names, emails, and passwords.

Also, we have created the userFormSchema using the Yup to validate the form. Here, we have defined rules so that the name should be at least three characters long and always required. The email should follow the format and always be required, and the password should be at least six characters long.

Also, we have given some styles to the input fields and error messages. When a user clicks the submit button, it invokes the handleFormSubmit() function, which gets the validation result by invoking the validateValues() function. It shows the output message based on the form validation.

import React, { useState } from "react";
import * as Yup from "yup";
import {
   StyleSheet,
   TouchableOpacity,
   View,
   TextInput,
   Text,
} from "react-native";
const App = () => {
   // creating the user form schema using Yup to validate name, email and password
   const userFormSchema = Yup.object().shape({
      name: Yup.string().min(3, "Too short").required("Required"),
      email: Yup.string().email("Invalid email").required("Required"),
      password: Yup.string().min(6, "Too short").required("Required"),
   });
   //  creating the styles for the elements
   const elementStyles = StyleSheet.create({
      container: {
         flex: 1,
         alignItems: "center",
         backgroundColor: "aqua",
         justifyContent: "center",
      },
      error: {
         marginBottom: 10,
         color: "red",
      },
      button: {
         backgroundColor: "#0084ff",
         width: "70%",
         borderRadius: 4,
         alignItems: "center",
         padding: 12,
      },
      input: {
         borderWidth: 2,
         padding: 15,
         marginBottom: 10,
         width: "70%",
         borderColor: "green",
         borderRadius: 4,
      },
      buttonText: {
         color: "#fff",
         fontSize: 16,
         fontWeight: "bold",
      },
   });
   // creating the state for the form
   const [initialValues, setInitialValues] = useState({
      name: "",
      email: "",
      password: "",
   });
   // creating the state for the errors
   const [errors, setErrors] = useState({});
   const [message, setMessage] = useState("");
   // creating the handleChange function to handle the change in the input fields
   function handleChange(key, val) {
      setInitialValues({ ...initialValues, [key]: val });
   }
   // creating the validateValues function to validate the form
   async function validateValues() {
      try {
         // validating the form using the userFormSchema
         await userFormSchema.validate(initialValues, { abortEarly: false });
         setErrors({});
      } catch (error) {
         //  if the form is invalid, then the errors are set to the state
         const newErrors = error.inner.reduce((acc, cur) => {
            acc[cur.path] = cur.message;
            return acc;
         }, {});
         setErrors(newErrors);
      }
   }
   // creating the handleFormSubmit function to handle the form submission
   function handleFormSubmit() {
      // validating the form values
      validateValues().then(() => {
         // set message based on the form is valid or invalid.
         if (Object.keys(errors).length === 0) {
         setMessage("Form is valid");
         } else {
            setMessage("Form is invalid");
         }
      });
   }
   return (
      // rendering the form
      <View style = {elementStyles.container}>
         {/* text inputs */}
         <TextInput
            style = {elementStyles.input}
            placeholder = "Name"
            value = {initialValues.name}
         onChangeText = {(value) => handleChange("name", value)}
         />
         {errors.name && <Text style = {elementStyles.error}> {errors.name} </Text>}
         <TextInput
            style = {elementStyles.input}
            placeholder = "Email"
            value = {initialValues.email}
            onChangeText = {(value) => handleChange("email", value)}
         />
         {errors.email && <Text style=  {elementStyles.error}> {errors.email} </Text>}
         <TextInput
            style = {elementStyles.input}
            placeholder = "Password"
            value = {initialValues.password}
            onChangeText = {(value) => handleChange("password", value)}
            secureTextEntry
         />
         {errors.password && (
            <Text style = {elementStyles.error}> {errors.password} </Text>
         )}
         {/* submit button */}
         <TouchableOpacity style = {elementStyles.button} onPress = {handleFormSubmit}>
            <Text style = {elementStyles.buttonText}> Submit Form </Text>
         </TouchableOpacity>
         <Text> {message} </Text>
      </View>
   );
};
export default App;

Output

Users learned to use the Yup with the react-native for the form validation. Rather than writing the custom form validation code, developers can use the libraries like Yup, which makes code more readable and easy.

Updated on: 24-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements