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
inputmodeare 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 called
- This is the step everything happens! In order to make changes, we need to watch the
creditCardNumberproperty. 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: