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