DEV Community

Cover image for NextJS - Form validations
EasyCode Sardar
EasyCode Sardar

Posted on

2 1

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>}
</div>

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})} />
{errors.city && errors.city.type === 'required' &&
<p className='text-danger'>Please enter city name</p>}
{errors.city && errors.city.type === 'minLength' &&
<p className='text-warning'>Please enter minimum 3 letters</p>}
</div>

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

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 ' + d.city);
}

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay