React Hook Forms
↩️ I chose this module to validate my forms, its lightweight and integrates with yup schemas. Plus a nice online form builder and right on point instructions.
You can see this form validation in action on my contact page and on my email form in a modali window, the button for the popup email form is in the email section at the lower part of every PubliusLogic page.
🔗 简体中文
React hook form validation without the hassle
- Super easy to integrate and create forms
- Built with React Hooks with performance and developer experience in mind
- Follows HTML standard for validation
- Tiny size without other any dependency
- Build forms quickly with the 🔗 form builder
Install
$ npm install react-hook-form
$ yarn add react-hook-form
For validation schemas use yup
$ npm install yup
$ yarn add yup
Yup at code sandbox
Docs
Quickstart
import React from 'react'
import useForm from 'react-hook-form'
function App() {
const { register, handleSubmit, errors } = useForm() // initialise the hook
const onSubmit = (data) => { console.log(data) } // callback when validation pass
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstname" ref={register} /> {/* register an input */}
<input name="lastname" ref={register({ required: true })} /> {/* apply required validation */}
{errors.lastname && 'Last name is required.'} {/* error message */}
<input name="age" ref={register({ pattern: /\d+/ })} /> {/* apply a Refex validation */}
{errors.age && 'Please enter number for age.'} {/* error message */}
<input type="submit" />
</form>
)
}
validationSchema
If you would like to centralize your validation rules or external validation schema, you can apply validationSchema when you invoke useForm. we use Yup for object schema validation and the example below demonstrate the usage.
import React from 'react'
import ReactDOM from 'react-dom'
import useForm from 'react-hook-form'
import * as yup from 'yup'
const SignupSchema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required(),
});
function App() {
const { register, handleSubmit, errors } = useForm({
validationSchema: SignupSchema
});
const onSubmit = data => {
console.log(data);
};
console.log(errors);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" name="name" ref={register} />
<input type="number" name="age" ref={register} />
<input type="submit" />
</form>
)
}
Contributors
Thanks goes to these wonderful people:
🔗 [AyumiKai]https://github.com/AyumiKai) 🔗 garthmcrae 🔗 [erikras]https://github.com/erikras)