logo
eng-flag

Yup Cheatsheet

Table of Contents

  1. Installation
  2. Basic Usage
  3. String Validation
  4. Number Validation
  5. Boolean Validation
  6. Date Validation
  7. Array Validation
  8. Object Validation
  9. Custom Validation
  10. Conditional Validation
  11. Error Handling
  12. Integration with React Hook Form

Installation

Install Yup:

npm install yup

Basic Usage

Basic schema definition and validation:

import * as Yup from 'yup';

const schema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required'),
  age: Yup.number().positive().integer().required('Age is required')
});

// Validate
schema.validate({ name: 'John', email: 'john@example.com', age: 30 })
  .then(() => console.log('Valid'))
  .catch(error => console.log('Error', error.errors));

String Validation

Various string validation methods:

const stringSchema = Yup.object().shape({
  username: Yup.string()
    .min(3, 'Username must be at least 3 characters')
    .max(20, 'Username must not exceed 20 characters')
    .matches(/^[a-zA-Z0-9]+$/, 'Username can only contain alphanumeric characters')
    .required('Username is required'),
  email: Yup.string()
    .email('Invalid email address')
    .required('Email is required'),
  password: Yup.string()
    .min(8, 'Password must be at least 8 characters')
    .matches(/[a-zA-Z]/, 'Password must contain at least one letter')
    .matches(/[0-9]/, 'Password must contain at least one number')
    .required('Password is required'),
  url: Yup.string()
    .url('Invalid URL')
});

Number Validation

Number validation methods:

const numberSchema = Yup.object().shape({
  age: Yup.number()
    .positive('Age must be a positive number')
    .integer('Age must be an integer')
    .min(18, 'Must be at least 18 years old')
    .max(100, 'Must be at most 100 years old')
    .required('Age is required'),
  price: Yup.number()
    .positive('Price must be positive')
    .round('ceil')
    .moreThan(0, 'Price must be greater than 0')
    .lessThan(1000000, 'Price must be less than 1,000,000')
});

Boolean Validation

Boolean validation:

const booleanSchema = Yup.object().shape({
  acceptTerms: Yup.boolean()
    .oneOf([true], 'You must accept the terms and conditions')
    .required('You must accept the terms and conditions'),
  subscribeNewsletter: Yup.boolean()
});

Date Validation

Date validation methods:

const dateSchema = Yup.object().shape({
  birthDate: Yup.date()
    .max(new Date(), 'Birth date cannot be in the future')
    .required('Birth date is required'),
  appointmentDate: Yup.date()
    .min(new Date(), 'Appointment date must be in the future')
    .required('Appointment date is required')
});

Array Validation

Array validation methods:

const arraySchema = Yup.object().shape({
  friends: Yup.array()
    .of(Yup.string())
    .min(1, 'Must have at least one friend')
    .max(5, 'Can have at most 5 friends'),
  scores: Yup.array()
    .of(Yup.number().positive().integer())
    .min(3, 'Must have at least 3 scores')
    .required('Scores are required')
});

Object Validation

Nested object validation:

const objectSchema = Yup.object().shape({
  user: Yup.object().shape({
    name: Yup.string().required('Name is required'),
    email: Yup.string().email('Invalid email').required('Email is required')
  }),
  address: Yup.object().shape({
    street: Yup.string().required('Street is required'),
    city: Yup.string().required('City is required'),
    zipCode: Yup.string().matches(/^d{5}$/, 'Invalid zip code')
  })
});

Custom Validation

Creating custom validation rules:

const customSchema = Yup.object().shape({
  username: Yup.string()
    .test('is-unique', 'Username is already taken', async (value) => {
      // Simulate API call to check username uniqueness
      const isUnique = await checkUsernameUniqueness(value);
      return isUnique;
    }),
  password: Yup.string()
    .test('is-strong', 'Password is not strong enough', (value) => {
      // Custom password strength check
      return /^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$/.test(value);
    })
});

Conditional Validation

Implementing conditional validation:

const conditionalSchema = Yup.object().shape({
  isEmployed: Yup.boolean(),
  companyName: Yup.string().when('isEmployed', {
    is: true,
    then: Yup.string().required('Company name is required when employed'),
    otherwise: Yup.string()
  }),
  phoneType: Yup.string().oneOf(['mobile', 'home']),
  phoneNumber: Yup.string().when('phoneType', {
    is: 'mobile',
    then: Yup.string().matches(/^d{10}$/, 'Must be a valid 10-digit mobile number'),
    otherwise: Yup.string().matches(/^d{7}$/, 'Must be a valid 7-digit home number')
  })
});

Error Handling

Handling validation errors:

const schema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required')
});

try {
  await schema.validate({ name: '', email: 'invalid' }, { abortEarly: false });
} catch (error) {
  if (error instanceof Yup.ValidationError) {
    const errorMessages = {};
    error.inner.forEach((err) => {
      errorMessages[err.path] = err.message;
    });
    console.log('Validation errors:', errorMessages);
  }
}

Integration with React Hook Form

Using Yup with React Hook Form:

import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';

const schema = Yup.object().shape({
  name: Yup.string().required('Name is required'),
  email: Yup.string().email('Invalid email').required('Email is required')
});

function Form() {
  const { register, handleSubmit, formState: { errors } } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("name")} />
      {errors.name && <p>{errors.name.message}</p>}
      
      <input {...register("email")} />
      {errors.email && <p>{errors.email.message}</p>}
      
      <input type="submit" />
    </form>
  );
}

2024 © All rights reserved - buraxta.com