Insert dash after every 4th character in input

I absolutely love this plugin for automatic formatting:
here.

So long as you’re already using JQuery, that is.

You could easily force the dashes in with a single line of code, like follows:

$("#credit").mask("9999-9999-9999-9999");

When the user types in the field, the dashes will automatically appear in the right spot, and they will not be able to delete them.

In addition, you can accommodate for different lengths or formats of credit cards with the ? character in your mask. For example, to accept inputs of 14 and 16 digits, you would do the following:

$("#credit").mask("9999-9999-9999-99?99");

Do keep in mind that this is only a client side validation


Edit: The mask plugin assumes that there is one, or finitely many, correct formats for the field. For example, there are only a few formats that credit card numbers come in. The plugin is there to ensure that your input will only be in one of those formats.

So technically, if you want a dash after every four digits, but for any number of digits, then this plugin is not right for you.

I would suggest you restrict the possible inputs to be reasonable, as there is certainly no such thing as a 1000-digit long credit card. But if you really want that functionality, you’ll have to write the script yourself or find another plugin. As of this time I’m not aware of one.

Leave a Comment