React Hook Form 7 - Email Validation Example
Example built with React Hook Form 7.43 and React 18.2
This is a quick example of how to validate an email input field in React with React Hook Form. For a more detailed registration form example that includes a bunch of other fields see React Hook Form 7 - Form Validation Example.
Here it is in action: (See on StackBlitz at https://stackblitz.com/edit/react-hook-form-7-email-validation-example)
React Hook Form Component with Email Validation
The app component contains an example form built with the React Hook Form library that contains a single email input field. The field has a required
validator and an email
validator, the email
validator tests that the input field contains a valid email address.
Form validation rules are defined with the Yup schema validation library and passed with the formOptions
to the React Hook Form useForm()
function, for more info on Yup see https://github.com/jquense/yup.
The onSubmit()
method is called when the form is valid and submitted, and simply displays the form data in a javascript alert.
import React from 'react';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';
function App() {
// form validation rules
const validationSchema = Yup.object().shape({
email: Yup.string()
.required('Email is required')
.email('Email is invalid')
});
const formOptions = { resolver: yupResolver(validationSchema) };
// get functions to build form with useForm() hook
const { register, handleSubmit, reset, formState } = useForm(formOptions);
const { errors } = formState;
function onSubmit(data) {
// display form data on success
alert('SUCCESS!! :-)\n\n' + JSON.stringify(data, null, 4));
return false;
}
return (
<div className="card m-3">
<h5 className="card-header">React Hook Form 7 - Email Validation Example</h5>
<div className="card-body">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="row">
<div className="col mb-3">
<label class="form-label">Email</label>
<input name="email" type="text" {...register('email')} className={`form-control ${errors.email ? 'is-invalid' : ''}`} />
<div className="invalid-feedback">{errors.email?.message}</div>
</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary me-1">Submit</button>
<button type="button" onClick={() => reset()} className="btn btn-secondary">Reset</button>
</div>
</form>
</div>
</div>
)
}
export { App };
Need Some React Hook Form Help?
Search fiverr for freelance React Hook Form developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!