Search code examples
javascriptreactjsformsvalidationmaterial-ui

How to change validation error message using react-hook-form-mui library?


I'm trying to learn react-hook-form-mui library. This project has quite short piece of documentation. I've tried different approaches but unfortunately none of them work. All I need is to add validation rule to my form field. Here is my functional component code.

export default function FormDialog({ showDialog, closeDialog }) {

    const onSumbit = (data) => {
        console.log(data)
    }

    const onError = (error) => {
        console.log(error)
    }

    const { register, setError, formState: { errors } } = useForm()

    return (
        <div>
            <Dialog
                open={showDialog}
                onClose={closeDialog}
                maxWidth={'xl'}
            >
                <FormContainer
                    onSuccess={onSumbit}
                    onError={onError}
                >
                    <DialogTitle>ADD Item</DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            Please fill form fields
                        </DialogContentText>
                            <div>
                                <TextFieldElement
                                    {...register("NAME", { required: "Error message" })} 
                                    sx={{ width: '100px' }}
                                    className={styles.formField}
                                    name={"NAME"}
                                    label={"Name"}
                                    required
                                />
                            </div>
                    </DialogContent>
                    <DialogActions>
                        <Button type={'submit'} variant={'contained'} color={'primary'}>
                            Submit
                        </Button>
                        <Button onClick={closeDialog}>Cancel</Button>
                    </DialogActions>
                </FormContainer>
            </Dialog>
        </div>
    );
}

As you can see I'm trying to use {...register(name, { options }) approach from react-hook-form v7 library but this doesn't seem to be the right way to do it and I get this object from console.log(error)

{"NAME":{"type":"required","message":"This field is required","ref":{}}}

instead of

{"NAME":{"type":"required","message":"Error message","ref":{}}}

Solution

  • According to the RHF MUI source code, the TextFieldElement component is already a controlled input that uses the Controller component, which means you don't need to register it again with the register method.

    Instead, the TextFieldElement has the validation prop that you can pass your validation rules into.

    <TextFieldElement name="NAME" validation={{ required: "Error message" }} />