Skip to main content

Yup Resolver

This resolver allows you to easily integrate the yup library as a validation method with react-hook-form. We provide the custom hook useYupValidationResolver, which includes validation methods tailored for Persian-specific fields and localized Persian error messages.


Custom Validation Methods

For your convenience, several custom validation methods for common scenarios in Persian forms have been added. By using these methods, you no longer need to extend Yup's base schema.

Available methods:

  • cellphone: For validating mobile phone numbers.
  • nationalId: For validating national ID codes.
  • postalCode: For validating postal codes.
  • onlyFaCharacters: For validating strings that contain only Persian characters.
  • onlyFaCharactersAndDigits: For validating strings that contain only Persian characters and digits.
  • space(count?: number): For validating the presence of spaces in a string.
  • halfSpace(count?: number): For validating the presence of half-spaces in a string.

Custom Configuration (Error Messages)

We have set up a global error map to translate Yup's default messages into Persian. This configuration is applied automatically, and no extra setup is required on your part.

TypeMethodError Message
mixedrequiredتکمیل این فیلد اجباری است
mixednotTypeفرمت مقدار وارد شده نامعتبر است
stringemailآدرس ایمیل وارد شده معتبر نمی‌باشد
stringminحداقل کارکتر ورودی باید --- باشد
stringmaxحداکثر کارکتر ورودی می‌تواند --- باشد
stringlengthطول کارکتر ورودی باید --- باشد
numberminحداقل مقدار ورودی باید --- باشد
numbermaxحداکثر مقدار ورودی می‌تواند --- باشد
numberintegerفقط استفاده از اعداد صحیح (بدون اعشار) معتبر می‌باشد
arrayminحداقل باید --- گزینه را انتخاب کنید
arraymaxحداکثر می‌توانید --- گزینه را انتخاب کنید

Usage with React Hook Form

You can directly use the useYupValidationResolver hook in place of the original yupResolver in your useForm call.

Practical Example:

import { useForm } from "react-hook-form";
import yup, { useYupValidationResolver } from "react-persian-form/resolvers/yup";

// 1. Define your validation schema
const schema = yup.object({
name: yup.string().required().onlyFaCharacters(),
mobile: yup.string().required().cellphone(),
});

function MyFormComponent() {
// 2. Create the resolver with your schema
const resolver = useYupValidationResolver(schema);

// 3. Pass the resolver to useForm
const { register, handleSubmit, formState: { errors } } = useForm({ resolver });

const onSubmit = handleSubmit((data) => {
console.log(data);
});

return (
<form onSubmit={onSubmit}>
<div>
<label>Name</label>
<input {...register("name")} />
<p>{errors.name?.message}</p>
</div>
<div>
<label>Mobile</label>
<input {...register("mobile")} />
<p>{errors.mobile?.message}</p>
</div>
<button type="submit">Submit</button>
</form>
);
};