Maddy
Maddy

Reputation: 2060

Using react input mask (InputMask) with formik

My question is somewhat similar to this SO question but I cannot get the value (just digits).

I have the following formikField

<Field
  name={`phoneNumber.value`}
  label="Phone Number"
  render={({ field }: any) => (
    <InputMask
      {...field}
      mask="(999) 999-9999"
      placeholder="Enter your phone number"
      type="text"
      onChange={(e: any) => {
        const val = e.target.value.match(/(\d+)/);
        console.log(val);
        formikProps.setFieldValue(
          `phoneNumber.value`,
          e.target.value,
        );
      }}
    />
  )}
  component={TextField}
/>

My value comes out like the following "value":"(213) 456-7883" but I just want digits(1234567883). I have looked through multiple threads related to formik but have not been able to get anywhere.

Is there a different approach to this?

Upvotes: 2

Views: 8111

Answers (1)

Wolfie
Wolfie

Reputation: 1381

You are setting the formik field value to the result of the Input Mask, which still contains the formatted text. If you only want digits, you can use a regex to remove all non-numeric values before setting the field value.

onChange={(e) => {
  formikProps.setFieldValue(
    'phoneNumber.value',
     e.target.value.replace(/\D/g, '') // removes all non-numeric characters
  );
}}

Additionally, you are attempting to match numerics with a regex, but then just using e.target.value, instead of using a regex and then passing that result to setFieldValue

Upvotes: 3

Related Questions