DEV Community

Cover image for NextJS - Form validations
EasyCode Sardar
EasyCode Sardar

Posted on

NextJS - Form validations

We are using react-hook-form:

Open Your NextJS profile inside IDE - VsCode

Create validate.js file inside pages folder, open it and use shortcut rfce for create basic reactjs function.

(You can change ext of validate.js file to validate.jsx if you want to use html shortcuts like div.row for row class to div.)

create couples of html divs with classes such card, card-body and form-group to display your UI of form

full name UI with error display
<div className="form-group p-4">
<label htmlFor="fullname">Full name</label>
<input className='form-control' {...register('fullname', {required:true})} />
{errors.fullname && errors.fullname.type == "required" && <p className='text-danger'>Please enter the full name</p>}

City name UI with error display
<div className="form-group p-4">
<label htmlFor="city">City Name</label>
<input className='form-control' {...register('city', {required:true, minLength:3})} />
{ && === 'required' &&
<p className='text-danger'>Please enter city name</p>}
{ && === 'minLength' &&
<p className='text-warning'>Please enter minimum 3 letters</p>}

Button UI
<div className="form-group p-4">
<input type="submit" className='btn btn-success' />

Import UseForm from react hook form
import { useForm } from 'react-hook-form'

const for register, handleSubmit and form state for errors
const {register, handleSubmit, formState:{errors}} = useForm();

Now add main function to alert the result
const myfun = (d) =>{
alert(d.fullname + ' from ' +;

Top comments (0)