sanniassin / react-input-mask

Input masking component for React. Made with attention to UX.
MIT License
2.22k stars 257 forks source link

Warning for using 'maxLength' to set correct credit card expiration date format on input autofill #228

Open danielppereira opened 4 years ago

danielppereira commented 4 years ago

I'm using react-input-mask in a payment form. The 'expiration date' input has the mask MM/YY.

Chrome saves credit card expiration year info in 4 digits format on it's wallet. When the user tries to use the Chrome autofill in any credit card field, choosing one card on his wallet, it set the first two digits of the year in the field.

ie: for the expiration date 31/2021, Chrome sets 31/20 in the field.

To solve this problem, I have to set maxlength="5" attribute in the 'expiration date' field. With that, I can get the last 2 digits of the year, and not the first 2 digits. (ie.: from the example above, I get 31/21)

It's all going well with the field validation and autocomplete funcionality, but when I run my tests with Jest, react-input-mask displays a warning:

Warning: react-input-mask: maxLength property shouldn't be passed to the masked input. It breaks masking and unnecessary because length is limited by the mask length.

How can I handle this credit card expiration date autofill problem without having this warning?

vladimir-fsh commented 3 years ago

try this one

<MaskedTextInput
    type="text"
    autocomplete="cc-exp"
    placeholder="MM/YY"
    beforeMaskedStateChange={({ currentState, nextState }) => {
      if (currentState && currentState.value.length === 7) {
        const [mm, year] = currentState.value.split('/');
        return {
          ...currentState,
          value: `${mm}/${year.substr(2)}`,
        };
      }
      return nextState;
    }}
    maskPlaceholder="MM/YY"
    mask={[/[0-1]/, /[0-9]/, '/', /[2-3]/, /[0-9]/]}
  />