Search code examples
javascriptjquerycoffeescript

Credit card number format


I'm trying to create a nifty credit card number input field that automatically formats a credit card number as a user types it in. Here's what I have:

# Whenever the credit card input changes, update its value.
$(".credit-card-number").on "input", ->

  # retrieve the credit card number
  creditCardNumber = $(this).val()

  # remove everything that's not a number
  creditCardNumber = creditCardNumber.replace(/[^\d]+/g, "")

  # ensure the value isn't more than 16 characters long
  creditCardNumber = creditCardNumber[0..15]

  # break apart the value every four numbers
  creditCardNumber = creditCardNumber.match(/.{1,4}/g)

  # insert spaces in the value when the value isn't null
  creditCardNumber = if creditCardNumber? then creditCardNumber.join(" ") else ""

  # set the value
  $(this).val(creditCardNumber)

This works perfectly on the following HTML:

<input class="credit-card-number" id="credit_card_number" name="credit_card_number" placeholder="Credit card number" type="text">

However, if I set the input's type to number, whenever I update the value and the value contains a space, Chrome changes the value to the empty string. Any ideas?


Solution

  • Scrap my previous answer.

    The reason that you can't have the space is because jQuery is performing a validation of sorts on the value you are trying to set. Space is not allowed in a number, and so it's clearing the value. The exact same thing happens when you enter a letter.

    There is nothing stopping you (at least in Chrome) from entering letters into a <input type="number"> field. It's just not valid and AFAIK if you submit the form, that field will contain an empty value (haven't tested this).