Validate CreditCard Number and Expiration Month and Year

3 fields that need to be validated in sync. Here’s a simple jQuery script to validate the credit card number, expiration month, expiration year.
Pending : Validate length of credit card

Credit Card : input type=”text” name=”card_num” id=”id_card_num”
Expiration Month : input type=”text” name=”exp_mon” id=”id_exp_mon” size=”2″ maxlength=”2″
Expiration Year : input type=”text” name=”exp_year” id=”id_exp_year” size=”4″ maxlength=”4″
Button (to submit) : input type=”button” value=”Submit” id=”id_submit”

$(document).ready(function() {
	$( "#id_submit" ).bind("click", submitForm);
	$( "#id_exp_mon" ).bind("blur", blurCcMonth);
});

var submitForm = function() {
	if(validForm()) {
		$( "form:first" ).submit();
	}
};

var validForm = function() {
	var $card_num = $( "#id_card_num" );
	var card_num = $card_num.val();
	//-- Credit card can only be numeric
	if (!$.isNumeric(card_num)) {
		alert("Please enter valid credit card.");
		$card_num.select();
		return false;
	}

	var $exp_mon = $( "#id_exp_mon" );
	var $exp_year = $( "#id_exp_year" );
	var exp_mon = $exp_mon.val();
	var exp_year = $exp_year.val();
	//-- Month can only be numeric
	if (!$.isNumeric(exp_mon)) {
		alert("Please enter valid expiration month.");
		$exp_mon.select();
		return false;
	}
	//-- Year can only be numeric
	if (!$.isNumeric(exp_year)) {
		alert("Please enter valid expiration year.");
		$exp_year.select();
		return false;
	}
	//-- Year must be in YYYY format
	if($.trim(exp_year).length < 4) {
		alert("Please enter year in format YYYY.");
		$exp_year.select();
		return false;
	}
	//-- Card expiration must be future month
	var currentYear = (new Date).getFullYear();
	var currentMonth = (new Date).getMonth() + 1;
	if (currentMonth.length < 2) {
		currentMonth = "0" + currentMonth;
	}
	var curYrMn = currentYear.toString() + currentMonth.toString();
	var expYrMn = exp_year + exp_mon;
	if (parseInt(expYrMn, 10) < parseInt(curYrMn, 10)) {
		alert("Please enter a future expiration date.");
		$exp_mon.select();
		return false;
	}

	return true;
};

var blurCcMonth = function() {
	var $exp_mon = $( this );
	exp_mon = $exp_mon.val();
	
	if ($.trim($exp_mon.val()).length == 0) {
		return;
	}
	else if($.trim($exp_mon.val()).length < 2) {
		exp_mon = "0" + $.trim($exp_mon.val());
		$exp_mon.val(exp_mon);
	}
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s