yup addMethod not working in typescript yup version
Asked Answered
D

2

6

yup package

Issue

When a custom method added to yup instance using the addMethod function, It produces the error below

TS2339: Property 'title' does not exist on type 'typeof import("node_modules/yup/lib/index")'

To Reproduce

yupInstance.ts file

import * as yup from 'yup';

function defaultTitleValidation(this: any, local: 'en' | 'bn') {
  return this.string().trim().required();
}

yup.addMethod(yup.string, 'title', defaultTitleValidation);

export default yup;

common.d.ts file

declare module 'yup' {
  interface StringSchema<TIn, TContext, TOut> {
    title(local: 'en' | 'bn'): any;
  }
}

myImplementationComponent.tsx

import yup from '../../../../common/yup';

const validationSchema = yup.object().shape({
  title_en: yup.title(), // TS2339: Property 'title' does not exist on type 'typeof import("node_modules/yup/lib/index")'
});
Devondevona answered 14/9, 2021 at 10:47 Comment(1)
Recently I also have encountered this same issue with yup package. Any answer will be highly appreciable.Clarinda
D
8

Solved by extending yup.BaseSchema interface.

declare module 'yup' {
  interface StringSchema<
    TType extends Maybe<string> = string | undefined,
    TContext extends AnyObject = AnyObject,
    TOut extends TType = TType,
  > extends yup.BaseSchema<TType, TContext, TOut> {
    title(local: 'en' | 'bn'): StringSchema<TType, TContext>;
  }
}

Custom method

function defaultTitleValidation(this: any, local: 'en' | 'bn') {
  return this.trim().required(); //before this.string().trim().required();
}

Implementation

const validationSchema = yup.object().shape({
  title_en: yup.string().title('en'),  //before yup.title(),
});
Devondevona answered 15/9, 2021 at 5:56 Comment(0)
M
1

I wanted to share this recent answer to adding custom methods to yub using nextjs 13 and typescript, here i write function arabicOrEnglish() to make sure text is in Arabic or English string:

1- Create file src/validations/schema/yupSchema.ts with this content:

import {StringSchema} from 'yup';

declare module 'yup' {
    interface StringSchema {
        arabicOrEnglish(): StringSchema;
    }
}

StringSchema.prototype.arabicOrEnglish = function () {
    return this.test('arabicOrEnglish', 'Must be in Arabic or English', function (value) {
        if (!value) {
            return true; // Skip validation for undefined values
        }
        const arabicRegex = /^[\u0600-\u06FF\s]+$/;
        const englishRegex = /^[A-Za-z\s]+$/;
        return arabicRegex.test(value) || englishRegex.test(value);
    });
};

2- Create file src/validations/schema/yupConfig.ts with this content:

import * as yup from 'yup';
import "@/validations/schema/yupSchema";

export default yup;

3- Now you can use this schema in any where like this class src/validations/signUpFormValidation.ts:

import yup from "@/validations/schema/yupConfig";

export const validationSchema = yup.object().shape({
    firstName: yup
        .string()
        .arabicOrEnglish()
});

4- And this is how you can use class in step 3 to validate forms:

import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from "react-hook-form";
import { validationSchema } from "@/validations/signUpFormValidation";

export const useSignUpForm = () => {
    const { register, handleSubmit, formState: { errors }, trigger } = useForm({
        resolver: yupResolver(validationSchema),
    });

    const onSubmit = handleSubmit(async (data) => {
        try {
            const response = await fetch("/api/user/signUp", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(data),
            });

            if (response.ok) {
                const responseData = await response.json();
                console.log(responseData); // Response from the API
                // Handle success or show success message to the user
            } else {
                throw new Error("Error creating user");
            }
        } catch (error) {
            console.error("Error creating user:", error);
            // Handle error or show error message to the user
        }
    });

    return { register, errors, onSubmit, trigger };
};
Maundy answered 9/7, 2023 at 7:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.