2
votes

I have a problem validating the length of the Tel No. in my React app. I need to validate the length that if it is less than the intended length, it should output the error.

Edit Input-masking-material-ui-formik-react-input-mask

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>
  );
};
1

1 Answers

2
votes

Looks like the val (in the function on test 3rd parameter) actually is considering the - and _ from the InputMask component. So 1 way to solve this is just to replace those symbols when you perform the validations

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

Edit Input-masking-material-ui-formik-react-input-mask (forked)