1

I'm trying to validate my input using formik/yup/material-ui/ and react-input-mask. From validationSchema only one option works correctly: .required. When i'm trying to validate by min/max length on the input it doesn't work properly.

When I set a mask for the input equals to: {"99 9999"} it looks like yup recognizes it like 7 characters(6 digits and one for space) and it doesn't change when I am typing in input field.

For example when I set: .min(7, "Password must contain at least 7 characters")

in validationSchema I will always get no errors even if I don't type anything in text field.

And when i set min(8, "Password must contain at least 8 characters") I will always get error feedback, even if I type something. Looks like the lenght of the input is always equals to length of the mask.

There is my input field:

 <InputMask
    mask={"99 9999"}
    value={name}
    onChange={change.bind(null, "name")}
  >
    {() => (
      <TextField
        id="name"
        name="name"
        variant="outlined"
        helperText={touched.name ? errors.name : ""}
        error={touched.name && Boolean(errors.name)}
        label="Name"
        fullWidth
      />
    )}
 </InputMask> 

And there you can see my whole code:

https://codesandbox.io/s/zrrxol5614

What am doing wrong?

4

2 回答 2

2

你的例子

const validationSchema = Yup.object({
  name: Yup.string("Enter a name")
  .required("Name is required")
  .min(7, "Password must contain at least 7 characters")
});

转换为未遮罩

const validationSchema = Yup.object({
  name: Yup.string("Enter a name")
  .required("Name is required")
  .transform(value => value.replace(/[^\d]/g, ''))
  .min(6, "Name must contain at least 6 characters")
});

为什么?

如果输入中存在占位符字符和空格,那么它们将与值一起发送给验证器。您可以沿途取消屏蔽它们或运行转换,如上所示。这种特殊的转换只是在验证之前从字符串中删除所有非数字,因此您必须根据需要进行更改。

于 2020-10-08T14:54:06.113 回答
0

您需要使用 trim()

const validationSchema = Yup.object({
  name: Yup.string()
  .required("Name is required")
  .test(value => value.trim().length > 6)
});

Trim 帮助您从输入掩码的输出中删除空间

于 2021-11-20T18:30:18.093 回答