yup addMethod在typescript yup版本中不工作



yup package

问题当使用addMethod函数将自定义方法添加到实例中时,它会产生以下错误

TS2339:类型'typeof import("node_modules/yup/lib/index")'上属性'title'不存在

繁殖

yupInstance。ts文件

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文件

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")'
});

通过扩展yup.BaseSchema接口解决。

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>;
}
}

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

实施

const validationSchema = yup.object().shape({
title_en: yup.string().title('en'),  //before yup.title(),
});

我想分享最近使用nextjs 13typescriptyub添加自定义方法的答案,在这里我编写函数arabicOrEnglish()以确保文本是阿拉伯语或英语字符串:

1-用以下内容创建文件src/validations/schema/yupSchema.ts:

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-u06FFs]+$/;
const englishRegex = /^[A-Za-zs]+$/;
return arabicRegex.test(value) || englishRegex.test(value);
});
};

2-用以下内容创建文件src/validations/schema/yupConfig.ts:

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

3-现在你可以在任何地方使用这个schema,像这个类src/validations/signUpFormValidation.ts:

import yup from "@/validations/schema/yupConfig";
export const validationSchema = yup.object().shape({
firstName: yup
.string()
.arabicOrEnglish()
});

4-这就是你如何在步骤3中使用class来验证表单:

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 };
};

最新更新