Skip to content
Advertisement

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 🙂

Advertisement

Answer

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
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement