Along with standard jQuery form validation, the jQuery masked input plugin provides a really nice way to preformat user-entered text. For example, a phone number might be masked so that it always ends up in the format "(999) 555-1234", even if the user just types in 9995551234 .

There are a number of ways this can be applied to a form, including the formatting of credit card numbers. Along with jQuery's validation methods for minlength and maxlength, you may also want to make sure the values entered are numeric only, or perhaps break up the user-entered data into hyphenated blocks, i.e. "9999-1234-1234-1234". This works really well and from what I can tell, helps cut down on errors due to mistyped card numbers.

However, not all credit cards use the same format. Amex is 13, Visa and others 16... and I believe there are some 14 or 15 digit variations.  The brilliant and thoughtful masked input plugin provides two solutions to this issue:

1) Variable (flexible) masking
With a recent release, you can now add a ? character to imply optional trailing digits
So, for an input that should accept 13-16 characters, like a credit card number:
    $('#cc-number').mask("9999999999999?999");
The same works for the CCV code, which can be either 3 or 4 digits
    $('#sec-code').mask("999?9");

2) Change the mask based on a user selection
Also introduced in a recent version, we now have the "unmask()" function.

So, to change the masking format based on the selection of another field - in this case, the type of credit card - is very easy.

In my form, I have a select box with the id of #cardType, which allows the user to select the type of card, and the options have values such as 'visa,amex,disc', etc.

To adjust the masking based on the user's card type, we simply need to grab the value of the dropdown when it is changed - if the value is 'amex' , set the mask for 13 digits, and 4 for the ccv (amex standard). If otherwise, set it to 16 and 3 digits. }

Here's my code, using unmask():

    // change mask for cc type
    $('#cardType').change(function(){
        var ctype = $(this).find('option:selected').attr('value');
        if(ctype=='amex'){
            // amex masking
            $('#
cc-number').unmask().mask("9999999999999");
            $('#
sec-code').unmask().mask("9999");
        } else {
            // standard masking
            $('#
cc-number').unmask().mask("9999999999999999");
            $('#
sec-code').unmask().mask("999");
        }
    });



Once again a superbly elegant and simple solution via jQuery.
From here, you can easily edit these rules to allow for specific masks based on other values.