How to install yup in react native in JavaScript?

Yup is a popular JavaScript schema validation library that integrates seamlessly with React Native applications. It provides a simple and powerful way to validate form data by defining validation schemas with various rules for different field types.

Installation

Install Yup in your React Native project using npm or yarn:

npm install yup

Or using Yarn:

yarn add yup

Basic Syntax

Create validation schemas using Yup's chainable API:

import * as Yup from 'yup';

const schema = Yup.object().shape({
   fieldName: Yup.string().required("This field is required"),
   email: Yup.string().email("Invalid email format").required("Required"),
   age: Yup.number().positive().integer().required("Required")
});

// Validate data
await schema.validate(formData);

Implementation Steps

  • Step 1: Import Yup and React Native components

  • Step 2: Define validation schema with field rules

  • Step 3: Create state for form data and error messages

  • Step 4: Implement form input handlers

  • Step 5: Create validation function using the schema

  • Step 6: Handle form submission with validation

Example 1: Basic Student Form

This example demonstrates a simple student information form with basic validation:

import React, { useState } from 'react';
import * as Yup from 'yup';
import { TouchableOpacity, View, TextInput, Text, StyleSheet } from 'react-native';

const App = () => {
   const userFormSchema = Yup.object().shape({
      student_id: Yup.string().required("Student ID is required"),
      age: Yup.number().required("Age is required").positive().integer(),
      portfolio: Yup.string().url("Must be a valid URL").nullable(),
   });

   const [studentInfo, setStudentInfo] = useState({
      student_id: "",
      age: "",
      portfolio: "",
   });
   const [message, setMessage] = useState("");

   function handleChange(key, value) {
      setStudentInfo({ ...studentInfo, [key]: value });
   }

   async function validateValues() {
      try {
         await userFormSchema.validate(studentInfo);
         setMessage("Form submitted successfully with no errors!");
      } catch (error) {
         setMessage(`Validation error: ${error.message}`);
      }
   }

   return (
      <View style={styles.container}>
         <TextInput
            style={styles.input}
            placeholder="Student ID"
            value={studentInfo.student_id}
            onChangeText={(value) => handleChange("student_id", value)}
         />
         <TextInput
            style={styles.input}
            placeholder="Age"
            value={studentInfo.age}
            onChangeText={(value) => handleChange("age", value)}
            keyboardType="numeric"
         />
         <TextInput
            style={styles.input}
            placeholder="Portfolio URL"
            value={studentInfo.portfolio}
            onChangeText={(value) => handleChange("portfolio", value)}
         />
         <TouchableOpacity style={styles.button} onPress={validateValues}>
            <Text style={styles.buttonText}>Submit Form</Text>
         </TouchableOpacity>
         <Text style={styles.message}>{message}</Text>
      </View>
   );
};

const styles = StyleSheet.create({
   container: {
      flex: 1,
      padding: 20,
      justifyContent: 'center',
   },
   input: {
      borderWidth: 1,
      borderColor: '#ccc',
      padding: 10,
      marginBottom: 10,
      borderRadius: 5,
   },
   button: {
      backgroundColor: '#007AFF',
      padding: 15,
      borderRadius: 5,
      alignItems: 'center',
      marginTop: 10,
   },
   buttonText: {
      color: 'white',
      fontWeight: 'bold',
   },
   message: {
      marginTop: 15,
      textAlign: 'center',
   },
});

export default App;

Example 2: Advanced User Registration Form

This example shows a more sophisticated form with detailed validation and error handling:

import React, { useState } from 'react';
import * as Yup from 'yup';
import {
   StyleSheet,
   TouchableOpacity,
   View,
   TextInput,
   Text,
} from 'react-native';

const App = () => {
   const userFormSchema = Yup.object().shape({
      name: Yup.string().min(3, "Name must be at least 3 characters").required("Name is required"),
      email: Yup.string().email("Invalid email format").required("Email is required"),
      password: Yup.string().min(6, "Password must be at least 6 characters").required("Password is required"),
   });

   const [formData, setFormData] = useState({
      name: "",
      email: "",
      password: "",
   });
   const [errors, setErrors] = useState({});
   const [message, setMessage] = useState("");

   function handleChange(key, value) {
      setFormData({ ...formData, [key]: value });
   }

   async function validateForm() {
      try {
         await userFormSchema.validate(formData, { abortEarly: false });
         setErrors({});
         return true;
      } catch (error) {
         const validationErrors = error.inner.reduce((acc, err) => {
            acc[err.path] = err.message;
            return acc;
         }, {});
         setErrors(validationErrors);
         return false;
      }
   }

   async function handleSubmit() {
      const isValid = await validateForm();
      if (isValid) {
         setMessage("Form submitted successfully!");
      } else {
         setMessage("Please fix the errors above");
      }
   }

   return (
      <View style={styles.container}>
         <TextInput
            style={styles.input}
            placeholder="Full Name"
            value={formData.name}
            onChangeText={(value) => handleChange("name", value)}
         />
         {errors.name && <Text style={styles.error}>{errors.name}</Text>}
         
         <TextInput
            style={styles.input}
            placeholder="Email Address"
            value={formData.email}
            onChangeText={(value) => handleChange("email", value)}
            keyboardType="email-address"
         />
         {errors.email && <Text style={styles.error}>{errors.email}</Text>}
         
         <TextInput
            style={styles.input}
            placeholder="Password"
            value={formData.password}
            onChangeText={(value) => handleChange("password", value)}
            secureTextEntry
         />
         {errors.password && <Text style={styles.error}>{errors.password}</Text>}
         
         <TouchableOpacity style={styles.button} onPress={handleSubmit}>
            <Text style={styles.buttonText}>Register</Text>
         </TouchableOpacity>
         <Text style={styles.message}>{message}</Text>
      </View>
   );
};

const styles = StyleSheet.create({
   container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      padding: 20,
      backgroundColor: '#f5f5f5',
   },
   input: {
      borderWidth: 2,
      padding: 15,
      marginBottom: 10,
      width: '90%',
      borderColor: '#4CAF50',
      borderRadius: 8,
      backgroundColor: 'white',
   },
   button: {
      backgroundColor: '#2196F3',
      width: '90%',
      borderRadius: 8,
      alignItems: 'center',
      padding: 15,
      marginTop: 10,
   },
   buttonText: {
      color: 'white',
      fontSize: 16,
      fontWeight: 'bold',
   },
   error: {
      color: 'red',
      marginBottom: 10,
      width: '90%',
   },
   message: {
      marginTop: 15,
      fontSize: 16,
      textAlign: 'center',
   },
});

export default App;

Common Validation Rules

Rule Usage Description
.required() Yup.string().required("Required") Field must have a value
.email() Yup.string().email("Invalid email") Must be valid email format
.min() Yup.string().min(3, "Too short") Minimum length/value
.positive() Yup.number().positive() Must be positive number

Conclusion

Yup simplifies form validation in React Native by providing a declarative schema-based approach. It reduces boilerplate code while offering comprehensive validation rules and clear error handling, making your forms more robust and user-friendly.

Updated on: 2026-03-15T23:19:01+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements