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.
Type | Method | Error Message |
---|---|---|
mixed | required | تکمیل این فیلد اجباری است |
mixed | notType | فرمت مقدار وارد شده نامعتبر است |
string | آدرس ایمیل وارد شده معتبر نمیباشد | |
string | min | حداقل کارکتر ورودی باید --- باشد |
string | max | حداکثر کارکتر ورودی میتواند --- باشد |
string | length | طول کارکتر ورودی باید --- باشد |
number | min | حداقل مقدار ورودی باید --- باشد |
number | max | حداکثر مقدار ورودی میتواند --- باشد |
number | integer | فقط استفاده از اعداد صحیح (بدون اعشار) معتبر میباشد |
array | min | حداقل باید --- گزینه را انتخاب کنید |
array | max | حداکثر میتوانید --- گزینه را انتخاب کنید |
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>
);
};