1
votes

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?

1
I've solved this problem by adding custom method to my validationSchema where I am checking that value of my input contains a character :"_". If it does I am returning false.Valke Allar

1 Answers

2
votes

Your Example

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

With Transform to Unmasked

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

Why?

If the placeholder characters and the space are present in the input, then they are going to be sent with the value to the validator. You can unmask them along the way or run a transform as shown above. This particular transform simply removes all non-digits from the string before validating, so you'd have to change it according to your needs.