Skip to content

Instantly share code, notes, and snippets.

@umschaudhary
Created December 5, 2022 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umschaudhary/de933a20a1a152fa9aac6ae08044588b to your computer and use it in GitHub Desktop.
Save umschaudhary/de933a20a1a152fa9aac6ae08044588b to your computer and use it in GitHub Desktop.
React with react-hook-form and yup for from validation
import React from 'react'
import { useForm } from 'react-hook-form'
import { object, string } from 'yup';
import { yupResolver } from '@hookform/resolvers/yup'
const UserRegistrationForm = () => {
const validationSchema = object().shape({
username: string()
.required('Username is required')
.min(3, 'Username must be at least 3 characters'),
email: string()
.required('Email is required')
.email('Invalid email address'),
password: string()
.required('Password is required')
.min(8, 'Password must be at least 8 characters'),
});
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: yupResolver(validationSchema)
})
// Form submission handler
const onSubmit = (data) => {
// Do something with the form data
}
return (
<div className="flex flex-col gap-4 w-1/2 m-auto">
<h1 className="bold text-2xl underline">Registration Form</h1>
<form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-2">
<div className="input-wrapper flex flex-col">
<label htmlFor="username">Username</label>
<input type="text" {...register('username')} />
{errors.username && (
<p className="text-xs italic text-red-500">{errors.username.message}</p>
)}
</div>
<div className="input-wrapper flex flex-col">
<label htmlFor="email">Email</label>
<input type="email" {...register('email')} />
{errors.email && <p className="text-xs italic text-red-500">{errors.email.message}</p>}
</div>
<div className="input-wrapper flex flex-col">
<label htmlFor="password">Password</label>
<input type="password" {...register('password')} />
{errors.password && (
<p className="text-xs italic text-red-500">{errors.password.message}</p>
)}
</div>
<div className="input-wrapper">
<button
type="submit"
className="focus:shadow-outline rounded bg-blue-500 py-2 px-4 font-bold text-white hover:bg-blue-700 focus:outline-none"
>
Submit
</button>
</div>
</form>
</div>
)
}
export default UserRegistrationForm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment