Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React hook form how to check if mails are equal

I wonder how to check if 2 inputs are equal? I mean I want to do form validation in which I will check if first input is the same as second one. Anyone knows how to do it?

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>
        Mail:
        <input {...register("mail", { required: true })} />
      </label>
      {errors.mail && <p>Mails are not matching</p>}
      <label>
        Confirm mail:
        <input {...register("mail", { required: true })} />
      </label>
      {errors.mail && <p>Mails are not matching</p>}
      <button type="submit">Send</button>
    </form>
  );
}

If something is unclear feel free to ask 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Its quite simple.
you get the values on onSubmit = (data) so you can access the fields from there.

also you can’t have 2 fields registered with the same name.
you can do this:

<label>
    Mail:
    <input {...register("mail", { required: true })} />
  </label>
  {errors.mail && <p>Mails are not matching</p>}
  <label>
    Confirm mail:
    <input {...register("confirmMail", { required: true })} />
  </label>

and for the matching,
here is an example how you do it

const { mail, confirmMail } = data;
    if (mail !== confirmMail) {
        // Codes here
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading