react-native-formik icon indicating copy to clipboard operation
react-native-formik copied to clipboard

Confused by formatting inputs example on home page

Open pkreipke opened this issue 6 years ago • 2 comments

In this example Formatting Inputs I'm confused by this line:

const formatPhoneNumber: string => string = (unformattedPhoneNumber) => ...;

Why the double function indirection? How exactly is that adding spaces? I'm guessing it's just a sample to say that if "value" prop is a function, it'll get called but store the value untransformed.

Would love some hints.

pkreipke avatar Apr 29 '19 22:04 pkreipke

Hmm. Anyone here that can help?

pkreipke avatar May 01 '19 20:05 pkreipke

@pkreipke Here's what I did to format as a US # (works in example app):

(lol github code tag fails on the block)

const formatPhoneNumber: string = phoneNumberString => {
  //normalize string and remove all unnecessary characters
  phoneNumberString = ('' + phoneNumberString).replace(/[^\d]/g, "");

  //check if number length is at least 10, if longer strip off the end characters
  if (phoneNumberString.length >= 10) {
    //reformat and return US phone number
    return phoneNumberString.substring(0,10).replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
  }

  //let them keep typing in their phone number
  return phoneNumberString
}

then in form:

<MyInput label="Cell" name="cell" value={formatPhoneNumber(props.values.cell)} />

function cobbled together from a few answers @ https://stackoverflow.com/questions/8358084/regular-expression-to-reformat-a-us-phone-number-in-javascript

ceonelson avatar Jun 11 '19 06:06 ceonelson