简体   繁体   中英

How to correctly validate an masked-input using material-ui, formik, yup, and react-input-mask?

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?

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.

You need to use trim()

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

Trim help you to remove space from the output of input mask

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM