Insert dash after every 4th character in input
I've fixed up your code, but still strongly suggest server validation and using four text boxes, and smartly switching between them:
$('.creditCardText').keyup(function() {
var foo = $(this).val().split("-").join(""); // remove hyphens
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
}
$(this).val(foo);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="creditCardText" />
View on jsFiddle
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.