MDB React & React Hook Form intergration
MDB React & React Hook Form intergration
MDB React integration with React Hook Form. Configuration, various examples of implementation and much more.
RHF is a library that makes dealing with forms in React easy. It is built with performance in mind. It allows you to create forms with minimal code and it is easy to integrate with MDB React.
In this tutorial you will learn how to validate forms created with MDB React using RHF.
Install React Hook Form
To install RHF, run the following command in your project directory:
You can find more details in the official documentation.
Basic example
In this form we will use the useForm hook to register
inputs and handleSubmit
to console log the form data.
The function will not be called if a required field is empty.
Default values
If the component you use has a value set by default, don't forget to pass it to the useForm
hook.
Basic validation
register
accepts an object as its second argument, which includes validation rules.
There are many options available, but the most commonly used are:
required
- field is requiredminLength
- minimum lengthmaxLength
- maximum lengthmin
- minimum valuemax
- maximum valuepattern
- regex patternvalidate
- custom function
The options can be passed with or without an error message.
Copy the code from this snippet below to see how it works in practice.
Open console and see how the error
object changes.
Invalid feedback
We already have some validation rules and different error messages. Let's check out how to display them.
Check this example.
Custom validation
Sometimes you may need to create a custom validation rule.
You can do it by passing a function to the validate
option.