3

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.