Integrating Yup with useForm for Validation
Showcase using Yup alongside useForm for schema-based validation, illustrating how to define a schema and apply it to a form for real-time validation feedback.
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
This code imports the necessary modules from 'react-hook-form' and 'yup', including the 'yupResolver' for integrating Yup with useForm.
const schema = yup.object({
name: yup.string().required('Name is a required field'),
email: yup.string().email('Must be a valid email').required('Email is required'),
age: yup.number().positive('Age must be positive').integer('Age must be an integer').required('Age is required')
});
Defines a Yup schema for validation, specifying requirements for various fields such as name, email, and age.
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: yupResolver(schema)
});
Sets up useForm with Yup validation by passing the schema through yupResolver to the resolver option.
const onSubmit = data => console.log(data);
Defines the onSubmit function that will log form data to the console.
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('name')} />
{errors.name && <p>{errors.name.message}</p>}
<input {...register('email')} />
{errors.email && <p>{errors.email.message}</p>}
<input {...register('age')} />
{errors.age && <p>{errors.age.message}</p>}
<button type='submit'>Submit</button>
</form>
);
The return statement in a React component that renders a form. It uses the register function from useForm to bind input fields to the schema and displays any error messages.