Blogging my journey of learning Full stack devlopment and creating an App to get a hands on knowledge.

Search This Blog

Tuesday, 31 January 2023

Add a Yup validation Schema to the react form using MUI as a UI component

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:

const {
        register,
        control,
        handleSubmit,
        formState: { errors }
    } = useForm({
        mode :'onTouched',
        resolver: yupResolver(formValidationSchema)
    });

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.

 <TextField sx={{
                  bgcolor: 'white',
                }}
            required
            id="invoiceID"
            name="invoiceID"
            fullWidth
            margin="dense"
            size="small"
            {...register('invoiceID')}
            error={errors.invoiceID ? true : false}
            onChange={(e) => handleHeaderInputChange(e)}
/>
<Typography color="error" sx={{ fontSize: '10px' }}>
   {errors.invoiceID?.message}
</Typography>

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


    invoiceID: Yup.number()
    .transform((_, val) => (val !== "" ? Number(val) : null))
    .nullable()
    .required('Invoice ID number is required'),

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



0 comments:

Post a Comment

Featured Post

Invoice Portal Project Links

Web App link for Invoice Portal  Invoice Portal App lets an user view and create an Invoice. Features: View the list of Number of Invoices b...

Powered by Blogger.

Popular Posts