Ensure that two TextField components in a React application, utilizing react-hook-form, contain equal values

I have created a form in which I need to validate if the values of two input fields are the same. The structure of my form is as follows:

function FormDataIcfes(){
            
    const classes = useStyles();  
    const {register, handleSubmit, control, errors} = useForm();
        return (
            <Box>
                <center>ICFES Data Form</center>
                <hr/>
                <form noValidate onSubmit={handleSubmit((data)=> console.log(JSON.stringify(data)))}>
                    <TextField
                    variant="outlined"
                    margin="normal"
                    inputRef={register({ required: true })}
                    required
                    fullWidth
                    type="number"
                    id="icfesDocument"
                    label="ICFES Document Presented"
                    name="icfesDocument"
                    autoComplete="number"
                    autoFocus
                    /> 
                    {errors.icfesDocument && <span className={classes.errors}>This field is required</span>}

                    <TextField
                    variant="outlined"
                    margin="normal"
                    inputRef={register({ required: true })}
                    required
                    fullWidth
                    id="snpIcfes"
                    label="SNP ICFES"
                    name="snpIcfes"
                    autoComplete="text"                    
                    />
                    {errors.snpIcfes && <span className={classes.errors}>This field is required</span>}
                    <TextField
                    variant="outlined"
                    margin="normal"
                    inputRef={register({ validate: value => value === **HERE snpIcfes VALUE** || 'error message' })}
                    required
                    fullWidth
                    id="snpIcfesConfirmation"
                    label="SNP ICFES Confirmation"
                    name="snpIcfesConfirmation"
                    autoComplete="text"                    
                    />   
                    {errors.snpIcfesConfirmation && <span className={classes.errors}>This field must match the SNP ICFES</span>}                 
                    
                    
                    <Button
                    type="submit"
                    fullWidth
                    variant="contained"
                    color="primary"
                    className={classes.submit}
                    >
                    Save
                    </Button>
                </form>
            </Box>
            );
}

The input fields we are comparing are named snpIcfes and snpIcfesConfirmation. How can I perform this validation using the register keyword? I am using Material-UI's TextField component along with react-hook-form.

Answer №1

you can utilize the getValues("id-input") function in this way:

inputRef={register({ validate: value => value === getValues("snpIcfes") || ' - must be equal to SNP ICFES' })}

refer to the documentation: https://react-hook-form.com/api#getValues

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetching data for React Select options via an AJAX call

How would you correct the selected option display issue in the following code snippet? <Select native value={item.resolution} onChange={this.handleChange} inputProps={{ name: 'student', id: 'student', ...

Why is my event.target.value not updating correctly in React useState?

My problem is that when I use useState, I am receiving incorrect numbers For example, if I print e.target.value it might display 1, but my selectedIndex shows 2. Similarly, when I have a selectedIndex of 0, it retrieves something different like 1. Any tho ...

Issue: Unable to locate the module '/app/apps/landing/server.js'

Objective: Arranging for the launch of an app using a global docker-compose Challenge: The issue lies in starting the app, specifically with this command node ./apps/landing/server.js which fails to locate the server.js file node: internal/modules/cjs/lo ...

Having trouble with the material-ui TextField Input while the Drawer is open?

I've been utilizing the Material-UI Autocomplete component (Free solo version) and everything was functioning smoothly until I integrated responsive behavior to the drawer using variant={!matchesSM ? 'persistent' : null}. <Drawer classN ...

Pictures will be displayed briefly for 1 second prior to the initiation of the JavaScript animation

I recently built a website using gatsby.js and incorporated bounce.js to animate some images on the page. Bounce.js is a JavaScript library that offers DOM animation functionalities. Although everything appears fine when I view the site locally, once I de ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

How do @material-ui/core and @types/material-ui interact with each other?

Exploring a sample project that utilizes material-ui. Upon inspecting the package.json file, I noticed the inclusion of the following packages: { ... "dependencies": { "@material-ui/core": "^1.4.1", ... }, "devDependencies": { "@types ...

Is it possible to show an image without altering the Box dimensions?

Hi there, I am currently working on designing a footer and I have encountered an issue. I want to add an image in a specific position, but when I do so, it affects the size of the box. I was wondering if there is a way to set the image as a background or b ...

Tips for decreasing the height of a cell or row in a React component

Currently, I am incorporating the table component in my React UI using Material-UI. Here is a link to the Material-UI Tables demo. I am looking to adjust the height of the rows or content cells within this table. The content rows are styled in alternating ...

Icon and text aligned in the center (React Material-UI)

I am trying to find the optimal way to display a React Material-UI component that includes both an icon and text, ensuring that they are all aligned vertically. Currently, I'm facing issues with this setup, especially when it comes to conditional rend ...

The webhook requests sent to the Stripe endpoint in a Next.js application hosted on Vercel were

I am currently working on a next.js project that is set up to receive events from Stripe using an API route. The code snippet below shows how this is implemented. Everything works perfectly fine when testing locally with the help of the Stripe CLI for rec ...

What is the best way to stop setInterval on click using React Hooks?

Recently, I attempted to restructure my code using react hooks. However, I encountered some challenges as the setInterval and setTimeout functions did not behave as expected when I copied and pasted them into hooks. After multiple attempts, I was able to m ...

Tips for verifying the presence of a 3D model from Spline API within the DOM using Next.js

I am in the process of developing a brand new website and I have integrated a 3D model from spline, although it is taking quite some time to load. To improve user experience, I decided to implement a loader/Spinner. However, I'm facing the challenge o ...

How come the back button does not initiate client-side navigation in a Next.js application?

In my Next.js application utilizing GraphQL to fetch articles from a server, I encountered an issue with dynamic routing when reloading the page while on an article and attempting to navigate back. The usual scenario works as expected: Index -> [slug] ...

The issue with text color not displaying properly within a Material-UI Theme

While designing a color theme using Material-UI, I specified the contrast text as white (#fff). Surprisingly, it seems to work for buttons with the primary color but not for those with the secondary color. I attempted overrides following the suggestions p ...

What causes errors when installing create next app with postcss?

Having trouble with the code in question? It's quite simple. There is an "app" folder containing a server directory inside. With a terminal open, I navigate to the app directory by using cd command. Then, I run the command npx create-next-app client w ...

Encountering an error while trying to install material-ui for React

Encountering an error during the installation of material-ui error Darwin 16.7.0 error argv "/Users/xyz/.nvm/versions/node/v7.5.0/bin/node" "/Users/xyz/.nvm/versions/node/v7.5.0/bin/npm" "install" "material-ui" 34 error node v7.5.0 35 error npm v4.1 ...

What is the process to alter the IconComponent of a NativeSelect based on whether it is open or closed?

In my customization of NativeSelect (in Material UI v3), I am aiming to dynamically change the IconElement based on whether the NativeSelect is open or closed. Unfortunately, it appears that using the open, onOpen, or onClose props with NativeSelect is not ...

What advantages does incorporating SSR with dynamic imports bring?

How does a dynamic imported component with ssr: true differ from a normal component import? const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), { ssr: true, }); What are the advantages of one method over the ...

Key attribute in React's li element

I received a caution that each child in an array or iterator should have a unique "key" prop, even though I did use a key. Below is the code snippet causing the issue: return ( <li onClick={this.handleOnMarkAsCompleted} key={Date.now()}> { com ...