使用 Formik + Yup 验证反应输入掩码长度

Validate react-input-mask length using Formik + Yup

我在验证 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>
  );
};

看起来 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")
});