I have a form to take credit card numbers. How can I force the following:
16 digits for a CC number, 15 if AmEx is selected from the select element
3 digits for a CSV number, 4 if AmEx is selected from the select element
2 digits for billingState (so it can only be NY, CA, NV, etc.)
5 digits for billingZip
(...) ... - .... format for phone numbers
Here's my code - http://slexy.org/view/s2dgDx7fV9
I'm using jQuery for much of the page. How can I do this in j开发者_如何学CQuery?
Thank you!
I suppose you should add some javascript code. Usual HTMl does not provide such powerful mechanizm to control user input.
Using jQuery you could check Credit Card Number like this:
function isAmExSelected()
{
return $("#creditCardType").val() == "American Express";
}
function containsOnlyDigits(str)
{
return str.match(/[^0-9]/) == null;
}
function validateCCNumber()
{
var ccn = $("#creditCardNumber").val();
var onlyDigits = containsOnlyDigits(ccn);
if(isAmExSelected())
{
return ccn.length == 15 && onlyDigits;
}
else
{
return ccn.length == 16 && onlyDigits;
}
}
function registerValidation(id, validateMethod, errorMethod)
{
$(id).change(function(){
if(validateMethod() == false)
{
errorMethod();
}
});
}
$(document).ready(function(){
registerValidation("#creditCardNumber", validateCCNumber, function(){alert("Error!")});
});
You should write other validations by yourself.
Bind your inputs to keyup events. Also, you can validate a card by the first digit, i.e. 4 = Visa, 5 = Mastercard, 3 = Amex (usually), and 6 = Discover.
$(document).ready( function(){
$("#creditCardNumber").change(function(){
$value = $(this).val();
$type = $value.substr(0,1);
if ( $type == '3' ){
$(this).attr("maxLength", 15);
}
else {
$(this).attr("maxLength", 16);
}
if ( $(this).attr("maxLength") < $value.length ) {
$len = ( $(this).attr("maxLength") - 1 );
$(this).val($value.substr(0,$len));
}
});
});
You can do something similar with CVV, or even get the value of the card type instead of the first digit. For state and zip, assuming you're only accepting US based addresses, you could just set the maxLength attribute in your HTML. As for the phone number mask, there is a jQuery plugin that I've never used so I can't vouch for it, but hopefully this will set you off in the right direction.
http://webdeveloperplus.com/jquery/how-to-mask-input-with-jquery/
精彩评论