【问题标题】:Validate react-input-mask length using Formik + Yup使用 Formik + Yup 验证反应输入掩码长度
【发布时间】:2025-12-20 06:55:11
【问题描述】:

我在我的 React 应用程序中验证电话号码的长度时遇到问题。我需要验证长度,如果它小于预期长度,它应该输出错误。

let validateSchema = yup.object().shape({
  tel_no: yup
    .string()
    .test("len", "Invalid Tel No.", (val) => val.length === 14)
    .required("Tel No. is required")
});

const PhoneForm = () => {
  return (
    <Container style={{ marginTop: "20px" }}>
      <Formik
        initialValues={{
          tel_no: ""
        }}
        validationSchema={validateSchema}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 500);
        }}
      >
        {({
          errors,
          values,
          setFieldValue,
          isSubmitting,
          touched,
          handleBlur,
          handleSubmit,
          handleChange
        }) => (
          <form onSubmit={handleSubmit}>
            <InputMask
              mask="99-999999999-9"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.tel_no}
            >
              {() => (
                <TextField
                  type="text"
                  label="Telephone Number (Ex: 56-452678899-8)"
                  name="tel_no"
                  fullWidth
                  variant="outlined"
                  helperText={touched.tel_no ? errors.tel_no : ""}
                  error={touched.tel_no && Boolean(errors.tel_no)}
                />
              )}
            </InputMask>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              disabled={isSubmitting}
            >
              Submit
            </Button>
          </form>
        )}
      </Formik>
    </Container>
  );
};

【问题讨论】:

    标签: reactjs material-ui react-hooks formik yup


    【解决方案1】:

    看起来val(在test 第三个参数的函数中)实际上正在考虑InputMask 组件中的-_。所以解决这个问题的一种方法就是在执行验证时替换这些符号

    let validateSchema = yup.object().shape({
      tel_no: yup
        .string()
        .test("len", "Invalid Tel No.", (val) => {
          const val_length_without_dashes = val.replace(/-|_/g, "").length;
          return val_length_without_dashes === 12;
        })
        .required("Tel No. is required")
    });
    

    【讨论】:

    • 谢谢。 “Tel No. is required”是空的时候没有出现吗价值已经
    • 我还注意到,当您立即单击提交按钮而不输入任何内容时。除非您触摸它,否则它不会输出错误消息。
    • 如果您打开开发工具并查看控制台,您将看到 val 在这一点上是 undefined(即您所描述的场景)。所以解决这个问题的一种方法是简单地为val 分配一个默认值(一个空字符串)。例如,(val = "") =&gt; { - 希望这会有所帮助
    • 你能用它来编辑你的 stackblitz 吗?谢谢