reactjs React:只有当字段可见时才进行条件验证

wpx232ag  于 2022-11-22  发布在  React
关注(0)|答案(2)|浏览(116)

我尝试在React中使用formik & yup实现表单验证。(名称、电子邮件、密码)。单击“创建帐户”按钮时,名称字段将按条件呈现。我希望仅当表单处于register状态时,名称字段才是必需的。我使用状态变量isLogin保存表单的当前状态,也使用它来初始化formik的initialValues中的showName布尔值。现在,名称字段没有应用验证,如果name字段为空,则可以提交表单。
我的代码

const [isLogin, setIsLogin] = useState(true);

const initialAuthFormValues = {
  hideName: isLogin, 
  name: "",
  email: "",
  password: "",
};

我的验证方案

const authFormValidationSchema = Yup.object().shape({
  hideName: Yup.boolean(),

  name: Yup.string().when("hideName",{
  is: false,
  then: Yup.string().required("Name is required"),
  }),

 email: Yup.string().required("Email is required"),
 password: Yup.string().required("Password is required"),
});

我的组件如下所示

<Formik
  initialValues={initialAuthFormValues}
  validationSchema={authFormValidationSchema}
  onSubmit={submitHandler}
>
  {(formik) => (
      <Form>
        {!isLogin && (
          <TextField
            label="Name"
            type="text"
            name="name"
            placeholder="Name"
          />
        )}
        <TextField
          label="Email"
          type="text"
          name="email"
          placeholder="Email"
        />
        <TextField
          label="Password"
          type="password"
          name="password"
          placeholder="Password"
        />
        <div className={classes.actions}>
          
          <Button type="submit"> {isLogin ? "Login" : "Create Account"} </Button>
          
          <Button
            type="reset"
            className="toggle"
            onClick={() => { setIsLogin((prevState) => !prevState); }}
          >
            {isLogin ? "Create new account" : "Login with existing account"}
          </Button>
        </div>
      </Form>
    </section>
  )}
</Formik>
xqkwcwgp

xqkwcwgp1#

您可以使用authFormValidationSchema作为状态,并在单击该按钮时更新此状态:

const authFormValidationSchema = {
 email: Yup.string().required("Email is required"),
 password: Yup.string().required("Password is required"),
};
const [authFormValidationSchema, setAuthFormValidationSchema] = useState(Yup.object());

跟踪useEffect中按钮被点击时的状态,并相应地更新authFormValues的状态:

useEffect(()=>{
  let authFormValidationSchema_ = JSON.parse(JSON.stringify(authFormValidationSchema))
  if(!buttonIsClicked)
  setAuthFormValidationSchema(Yup.object(authFormValidationSchema_));
  else  setAuthFormValidationSchema(Yup.object({...authFormValidationSchema_, name: Yup.string().required("Name is required") }));
  },[buttonIsClicked]);
zujrkrfu

zujrkrfu2#

终于找到了解决问题的办法:在我的代码中,动作是我的道具
1.首先,在JS中创建一个变量,用于保存逻辑:

let passwordTest
      
if (action === "Register") {
  passwordTest = {
    password2: Yup
      .string().trim()
      .required("Please confirm your password")
      .oneOf([Yup.ref('password'), null], 'Passwords must match')
} else {
   passwordTest = null
}

基本上,上面你说,如果道具是注册(如果此表单是为注册目的而不是登录而呈现的),那么创建字段应用列出的验证,否则,此字段将为空。
1.然后,在Yup模式中解构变量:

const validationSchemaYup = Yup.object().shape({

other fields validation logic...
...passwordTest,
other fields validation logic...

在这里你添加你的新的自定义验证逻辑,别忘了解构!

相关问题