In the world of applications, forms are everywhere—signing up for an account, entering payment details, applying for loans, and more. Ensuring that these forms work correctly and securely is crucial. That's where form validation comes in. In this guide, we'll explore how to implement effective form validation in your fintech applications using React Hook Form and Yup, two powerful tools that make the process straightforward and efficient.
useForm
hook from React Hook Form and pass in the Yup schema using the resolver:onSubmit
function is called only if all validations pass. If there are validation errors, they are displayed next to the respective fields.npm install react-hook-form yup @hookform/resolvers
import * as Yup from 'yup'; const validationSchema = Yup.object().shape({ fullName: Yup.string() .required('Full name is required') .min(2, 'Full name must be at least 2 characters'), email: Yup.string() .email('Invalid email address') .required('Email is required'), phoneNumber: Yup.string() .matches(/^[0-9]{10}$/, 'Phone number must be 10 digits') .required('Phone number is required'), password: Yup.string() .required('Password is required') .min(8, 'Password must be at least 8 characters'), });
import { useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; const { register, handleSubmit, formState: { errors } } = useForm({ resolver: yupResolver(validationSchema), });
<form onSubmit={handleSubmit(onSubmit)}> <div> <label>Full Name</label> <input type="text" {...register('fullName')} /> {errors.fullName && <p>{errors.fullName.message}</p>} </div> <div> <label>Email</label> <input type="email" {...register('email')} /> {errors.email && <p>{errors.email.message}</p>} </div> <div> <label>Phone Number</label> <input type="text" {...register('phoneNumber')} /> {errors.phoneNumber && <p>{errors.phoneNumber.message}</p>} </div> <div> <label>Password</label> <input type="password" {...register('password')} /> {errors.password && <p>{errors.password.message}</p>} </div> <button type="submit">Register</button> </form>
const validationSchema = Yup.object().shape({ hasReferral: Yup.boolean(), referralCode: Yup.string().when('hasReferral', { is: true, then: Yup.string().required('Referral code is required'), otherwise: Yup.string().notRequired(), }), });