Mastering Scalable Form Validation Using React Hook Form + Yup in React native (or React).
Building scalable and reusable forms is essential in any large-scale application. This guide outlines how to implement a robust and maintainable form system using:
- React Hook Form β for managing form state and handling submission
- Yup β for schema-based validation
- @hookform/resolvers β to connect Yup schemas with React Hook Form
Installation
Step 1: Define Scalable Schema Methods
Instead of defining validation logic in each form, centralize it once in a shared utility. This makes validation consistent and reusable across the app.
π Validation Schema File:
π View yupFormSchema.js on GitHub
This file includes pre-defined reusable methods like:
- string(), email(), integer(), boolean()
- relationToOne(), relationToMany()
- date(), datetime(), decimal(), files(), images() etc.
Each method accepts label and config for customization and builds the schema accordingly.
Step 2: Define Form Schema Using Central Schema Helpers
Hereβs how you use the helpers from yupFormSchema.js to create a registration schema:
Step 3: Set Up React Hook Form
Now bind the schema to react-hook-form:
Wrap your form inputs inside FormProvider to share context:
Step 4: Create a Reusable <InputFormItem /> Component
This custom component handles everything: field registration, value changes, validation error display, etc.
β It automatically registers the field
β Syncs field value using watch and setValue
β Displays field-level validation errors
Final Step: Handle Submission
You can directly bind the form submission handler like this:
Where onSubmit is your custom submission handler:
β Benefits of This Architecture
- π Reusability: Write validation logic once and reuse across the app.
- β»οΈ Scalability: Add new types easily in yupFormSchema.js.
- π§Ό Separation of Concerns: Keeps your form component clean and readable.
- π Type-safe & Customizable: Extend or override each field config as needed.