Format a Card Number

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

A payment form has a text input labelled "Card number" (keep it type="text") and a "Pay" button. As you type, keep only the digits, at most 16 of them, and show them in groups of four separated by single spaces: typing 4242424242424242 shows "4242 4242 4242 4242". Anything else typed (letters, spaces, dashes) is dropped, and there's never a space at the end, so 12345678 shows "1234 5678" and Backspace after "1234 5" leaves "1234". Typing and deleting only happen at the end of the input here. Pay is disabled until there are 16 digits; clicking it replaces the form with "Paid with the card ending 4242" (the last four digits).

Your code must pass

  • Digits are grouped in fours as you type
  • Other characters are dropped
  • It stops at 16 digits
  • Backspace deletes digits cleanly
  • Pay needs 16 digits and names the last four