React Hook Form is a React library that is used to make performant, flexible, and extensible forms with easy-to-use validation support.
Dependencies
npm i react-hook-form
Pass the rules to the React Hook Form useForm() function using yupResolver() function
Then inside your component, you can use the hook:
The useForm hook takes and returns two objects containing few properties:
mode : It can be passed to useForm hook if you want to validate the field whenever there is an onChange event for example. the possible values are onChange, onBlur, onSubmit, onTouched, all. With onSubmit being the default value
resolver : This function allows you to use any external validation library such as Yup and many others
register : is a function to be assigned to each input field ref so that React Hook Form can track the changes for the input field value
handleSubmit : is the function that is called when the form is submitted
errors : is an object that will contain the validation errors of each input if any
control: register components, work with Controller (wrapper component for controlled inputs)
Define a MUI textField for which you want to do validation and a error under it.
We register form fields with the React Hook Form by calling the register function above with the field name of input element {...register('fieldname')}.
If error object contains the invoiceID field, the error message will be displayed.
Define the yup validation schema
Dependencies
npm i yup
Since I have defined the mode to onTouched in react useForm hook ,form will also be validated whenever there is click on the Textfield along with its default validation on Submit