Hey Dev.to community!
Recently when I was working on a project I encountered a very good problem (yes problems are good)! What I simply wanted to do was to create a field for credit cards with auto-dashing. Meaning that I wanted a dash (-) character between every 4 digits. I've searched through the net but people were overcomplicating the matter and finally, I've got to do it myself :)))). Here is the Codepen that I am sharing with you of the solution I found out and thought it might be useful for some people as well. I didn't add anything extra except for a small SCSS so the field doesn't look so crappy :). To be honest, I hate when people add a lot of unnecessary stuff to a simple code snippet. It makes it confusing!.
So here is the simple explanation:
- Obviously, you need an input field! I made a simple text field since I don't need a number field. You can later make it to only accept numbers. The
pattern
andinputmode
are only for mobiles to understand that they should bring up a numeric keyboard. You can ignore these two attributes if you want. Max length is 19 which is 16 + 3. 16 digits for the card number and 3 dashes maximum. I've bound this input to a Vue data calledcreditCardNumber
. - This is the step everything happens! In order to make changes, we need to watch the
creditCardNumber
property. First, we get the real card number. The real card number only consists of digits without dashes. Be careful! If you don't implement this step the watch will dive deep into an infinite loop! Next, we split the real number using anything from 1 character to 4 characters using RegEx. Now we have an array that we can join by dash character! Finally, we replace the dashed number with the current one and we are done!
Keep in mind I've simplified the problem. You can limit the field to numbers only using extra RegEx or other methods.
I hope this comes in handy someday for someone!
BTW check out my Vue cheatsheet if you are starting to learn Vue:
Top comments (4)
Thanks for this simple and useful code. Maybe someday I'll use it. In the meantime, I have other problems. I can't fix my name in the banking system in any way. I've already contacted my Mortgage Advice Lincoln, to help me, but this person is working with my mortgage and its payment, not the code and technical problems. The problem is that everyone writes names on maps in capital letters in our country. If I move, no one will send money to me right away because they won't think to write my first and last name in all capital letters and will receive errors.
Simple and useful. Nice!
thanks for the tip :)
Thanks !!!