最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate password and confirm password in react-hook-form version 7 - Stack Overflow

programmeradmin3浏览0评论

I am using react-form-hook. I am trying to match the password and confirm the password. But it is not working and validation not get triggered.

This is the password input react-form-hook.

<div className="mb-4">
        <label className="input-label" htmlFor="password">
          Password
        </label>
        <input
          {...register("password", {
            required: true,
            minLength: {
              value: 8,
              message: "Password must have at least 8 characters",
            },
          })}
          className="input-field"
          id="password"
          type="password"
          placeholder="********"
        />
        {errors.password && (
          <p className="text-red-500">{errors.password.message}</p>
        )}
      </div>
      <div className="mb-4">
        <label className="input-label" htmlFor="confirmPassword">
          Confirm Password
        </label>
        <input
          {...register("password_repeat")}
          className="input-field"
          id="confirmPassword"
          type="password"
          placeholder="********"
        />
        {errors.password_repeat && (
          <p className="text-red-500">{errors.password_repeat.message}</p>
        )}
      </div>

handler

  const {
  register,
  watch,
  handleSubmit,
  formState: { errors, dirtyFields },
  } = useForm();
  const password = useRef({});

  password.current = watch("password", "");

submit form method.

const onSubmit = async (data, e) => {
e.preventDefault();
await createUserWithEmailAndPassword(data.email, data.password);
};

I am using react-form-hook. I am trying to match the password and confirm the password. But it is not working and validation not get triggered.

This is the password input react-form-hook.

<div className="mb-4">
        <label className="input-label" htmlFor="password">
          Password
        </label>
        <input
          {...register("password", {
            required: true,
            minLength: {
              value: 8,
              message: "Password must have at least 8 characters",
            },
          })}
          className="input-field"
          id="password"
          type="password"
          placeholder="********"
        />
        {errors.password && (
          <p className="text-red-500">{errors.password.message}</p>
        )}
      </div>
      <div className="mb-4">
        <label className="input-label" htmlFor="confirmPassword">
          Confirm Password
        </label>
        <input
          {...register("password_repeat")}
          className="input-field"
          id="confirmPassword"
          type="password"
          placeholder="********"
        />
        {errors.password_repeat && (
          <p className="text-red-500">{errors.password_repeat.message}</p>
        )}
      </div>

handler

  const {
  register,
  watch,
  handleSubmit,
  formState: { errors, dirtyFields },
  } = useForm();
  const password = useRef({});

  password.current = watch("password", "");

submit form method.

const onSubmit = async (data, e) => {
e.preventDefault();
await createUserWithEmailAndPassword(data.email, data.password);
};
Share Improve this question edited May 1, 2022 at 7:13 DevThiman 1,1381 gold badge14 silver badges28 bronze badges asked May 1, 2022 at 6:29 Tamal MallickTamal Mallick 991 gold badge3 silver badges6 bronze badges 1
  • I put an answer below and let me know if it solved your issue. – DevThiman Commented May 1, 2022 at 10:14
Add a ment  | 

2 Answers 2

Reset to default 4

There are two methods [ getValues and watch ] provided by react-hook-form to get the current value of the form-fields. We can check the password and confirmpassword fields value from this methods and use it for to generate validation messages.

const { register, handleSubmit, getValues, watch, formState: { errors } } = useForm();

const onSubmit = (data) => {
  console.log(data);
};

<form onSubmit={handleSubmit(onSubmit)}>
  {/* register your input into the hook by invoking the "register" function. Here we can register the validations rules also */}
  <input
    {...register("password", {
      required: true,
      minLength: 5
    })}
    id="password"
    type="password"
    placeholder="********"
  />
  {errors?.password?.type === "required" && <p>This field is required</p>}
  {errors?.password?.type === "minLength" && (
    <p>password cannot less than 5 characters</p>
  )}
  {/* include validation with required or other standard HTML validation rules */}
  <input
    {...register("password_repeat", { required: true })}
    id="password"
    type="password"
    placeholder="********"
  />
  {/* errors will return when field validation fails  */}
  {/* here we watch the both password and confirm password filed and if both not match, trigger the validation */}
  {watch("password_repeat") !== watch("password") &&
  getValues("password_repeat") ? (
    <p>password not match</p>
  ) : null}

  <input type="submit" />
</form>

Check this demo password-match react-hook-form for full demonstration.

Use validate to password field. Hope it work.

<input type='password' placeholder="Enter Confirm Password"
                           {...register("confirm_password", {
                               required: {
                                   value: true,
                                   message: 'Confirm password is required'
                               },
                               validate: {
    
                                   confirmEmail: (fieldValue) => {
                                       fieldValue === getValues('password') || "password not match"
                                   }
    
                               }
                           })}
                    />
发布评论

评论列表(0)

  1. 暂无评论