You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PasswordStrengthBar和useForm时如何在输入强密码前禁止提交请求

实现方案

你可以通过新增密码强度得分的状态绑定,结合react-hook-form的自定义校验规则实现需求,修改后的代码如下:

import { useState } from 'react';
import { useForm } from 'react-hook-form';

// 组件内部逻辑
const { register, watch, handleSubmit, formState: { errors } } = useForm();
// 新增状态存储密码强度得分
const [pwdScore, setPwdScore] = useState(0);

// 提交逻辑,只有校验全部通过才会执行
const onSubmit = (data) => {
  // 此处写你的提交请求逻辑
  console.log('提交的密码符合要求', data);
}

return (
  <form onSubmit={handleSubmit(onSubmit)}>
    <Grid container className={classes.inputItem}>
      <Grid item>
        <Input
          name="newPassword"
          type={state.new ? "text" : "password"}
          inputClassName={classes.Input}
          ref={register({ 
            required: "请输入新密码",
            // 新增自定义校验规则,根据密码强度得分判断
            validate: () => pwdScore >= 3 || "请设置强密码后再提交"
          })}
          error={!!errors.newPassword}
          // 可在密码输入框下方展示校验错误提示
          helperText={errors.newPassword?.message}
          endAdornment={
            <PasswordAdornment
              onClick={(visible) => dispatch({ field: "new", visible })}
            />
          }
        />
        <PasswordStrengthBar
          name="PasswordStrength"
          password={watch("newPassword")}
          minLength={6}
          barColors={barColors}
          scoreWordClassName={classes.scoreWordClassName}
          // 新增onChange回调获取实时强度得分,不同组件返回的score范围可能有差异,可根据实际调整阈值
          onChange={(score) => setPwdScore(score)}
        />
      </Grid>
    </Grid>
    {/* 提交按钮 */}
    <button type="submit">提交</button>
  </form>
)

说明

  • 常用的PasswordStrengthBar组件默认会通过onChange回调返回0-4的强度得分,通常3对应强、4对应极强,你可以根据自己的业务要求调整校验阈值
  • react-hook-form的validate自定义校验返回false或错误提示文本时,会判定校验不通过,阻止handleSubmit绑定的提交逻辑执行,同时错误信息会同步到errors.newPassword中
  • 若你使用的PasswordStrengthBar组件没有提供onChange回调,也可以自己引入密码强度校验逻辑,监听watch("newPassword")的变化计算强度,再写入状态做校验即可

内容的提问来源于stack exchange,提问作者zahra zamani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 11:42:02