javascript验证_使用JavaScript验证信用卡

javascript验证

We all know that JavaScript shouldn't be a web form's only method of validation but client side validation does prevent unnecessary server side processing when user input is obviously invalid.  I'd also consider client side form validation a usability booster (...or nightmare when done poorly.)  I often hear developers complain about how difficult validating credit cards can be, especially when only supporting specific credit cards.  Luckily the Dojo Toolkit includes dojox.validate.creditCard, a resource capable of efficiently validating a credit card.  Better yet, you can easily take its logic and create you own validator.

我们都知道JavaScript不应只是Web表单的唯一验证方法,但是当用户输入显然无效时,客户端验证确实可以防止不必要的服务器端处理。 我还会考虑对客户端表单进行验证,这会增强可用性(...或做得不好时的噩梦。)我经常听到开发人员抱怨验证信用卡有多困难,尤其是仅支持特定信用卡时。 幸运的是,Dojo工具包包含dojox.validate.creditCard ,该资源能够有效地验证信用卡。 更好的是,您可以轻松地采用其逻辑并创建自己的验证器。

Dojo JavaScript (The Dojo JavaScript)

The validation code is quite compact but well-commented;  read those comments as you look at the code:

验证代码非常紧凑,但是注释很好。 在查看代码时,请阅读这些注释:


dojo.provide("dojox.validate.creditCard");
/*=====

	dojox.validate.creditCard = {
		// summary:
		//		Module provides validation functions for Credit Cards, using account number
		//		rules in conjunction with the Luhn algorigthm, with a plugable card info database.
	};
	
=====*/
dojo.require("dojox.validate._base");

dojox.validate._cardInfo = {
	// summary: A dictionary list of credit card abbreviations
	//
	// description:
	//
	//		A hash of valid CC abbreviations and regular expressions
	//
	//		mc: Mastercard
	//		ec: Eurocard
	//		vi: Visa
	//		ax: American Express
	//		dc: Diners Club
	//		bl: Carte Blanch
	//		di: Discover
	//		jcb: JCB
	//		er: Enroute
	//
	//	example:
	//		Define your own card, gift-card, whatever. Starts with 7,
	//		is 15 total length.
	//	| dojo.mixin(dojox.validate._cardInfo, {
	//	| 	"my":"7[0-9]{14}"
	//	| });
	
	'mc':'5[1-5][0-9]{14}',
	'ec':'5[1-5][0-9]{14}',
	'vi':'4(?:[0-9]{12}|[0-9]{15})',
	'ax':'3[47][0-9]{13}',
	'dc':'3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
	'bl':'3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
	'di':'6011[0-9]{12}',
	'jcb':'(?:3[0-9]{15}|(2131|1800)[0-9]{11})',
	'er':'2(?:014|149)[0-9]{11}'
}

dojox.validate.isValidCreditCard = function(value, ccType){
	// summary: Validate a credit card number by type with Luhn checking.
	//
	// description:
	//		Checks if a credit card type matches the # scheme in a passed value, and if
	//		the Luhn checksum is accurate (unless its an Enroute card, in which case
	//		the checkSum is skipped), returning a Boolean to check against.
	//
	// value: String|Int
	//		A Value (credit card number) to validate
	//
	// ccType: String
	//		A credit-card abbreviation.
	//
	// example:
	// |	if(dojox.validate.isValidCreditCard("12345", "mc")){
	// |		console.log('inconceivable');
	// |	}
	
	return ((ccType.toLowerCase() == 'er' || dojox.validate.isValidLuhn(value)) &&
			dojox.validate.isValidCreditCardNumber(value, ccType.toLowerCase())); // Boolean
}

dojox.validate.isValidCreditCardNumber = function(value, ccType){
	// summary:
	//		Checks if value matches the pattern for that card or any card types if none is specified
	//
	// value: String|Int
	//		CC #, white spaces and dashes are ignored
	//
	// ccType: String?
	//		One of the abbreviation values in `dojox.validate._cardInfo` --
	//		if Omitted, function returns a `|` delimited string of matching card types,
	//		or false if no matches found.

	value = String(value).replace(/[- ]/g,''); //ignore dashes and whitespaces

	var cardinfo = dojox.validate._cardInfo, results = [];
	if(ccType){
		var expr = '^' + cardinfo[ccType.toLowerCase()] + '$';
		return expr ? !!value.match(expr) : false; // boolean
	}

	for(var p in cardinfo){
		if(value.match('^' + cardinfo[p] + '$')){
			results.push(p);
		}
	}
	return results.length ? results.join('|') : false; // String | boolean
}

dojox.validate.isValidCvv = function(/* String|Int */value, /* String */ccType) {
	// summary:
	//  	Validate the security code (CCV) for a passed credit-card type.
	//
	// description:
	//
	// value:
	
	if(!dojo.isString(value)){
		value = String(value);
	}
	var format;
	switch (ccType.toLowerCase()){
		case 'mc':
		case 'ec':
		case 'vi':
		case 'di':
			format = '###';
			break;
		case 'ax':
			format = '####';
			break;
	}
	
	return !!format && value.length && dojox.validate.isNumberFormat(value, { format: format }); // Boolean
}



You would use the code above by requiring the resource and running the isValidCreditCard method, passing the value and card type.  But what if you don't use the Dojo Toolkit?  You can pull the code out of Dojo and into your own application:

您将需要资源并运行isValidCreditCard方法,传递值和卡类型来使用上面的代码。 但是,如果您不使用Dojo Toolkit,该怎么办? 您可以将代码从Dojo中拉出,并放入自己的应用程序中:


// Create an object
var creditCardValidator = {};
// Pin the cards to them
creditCardValidator.cards = {
	'mc':'5[1-5][0-9]{14}',
	'ec':'5[1-5][0-9]{14}',
	'vi':'4(?:[0-9]{12}|[0-9]{15})',
	'ax':'3[47][0-9]{13}',
	'dc':'3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
	'bl':'3(?:0[0-5][0-9]{11}|[68][0-9]{12})',
	'di':'6011[0-9]{12}',
	'jcb':'(?:3[0-9]{15}|(2131|1800)[0-9]{11})',
	'er':'2(?:014|149)[0-9]{11}'
};
// Add the card validator to them
creditCardValidator.validate = function(value,ccType) {
	value = String(value).replace(/[- ]/g,''); //ignore dashes and whitespaces

	var cardinfo = creditCardValidator.cards, results = [];
	if(ccType){
		var expr = '^' + cardinfo[ccType.toLowerCase()] + '$';
		return expr ? !!value.match(expr) : false; // boolean
	}

	for(var p in cardinfo){
		if(value.match('^' + cardinfo[p] + '$')){
			results.push(p);
		}
	}
	return results.length ? results.join('|') : false; // String | boolean
};

With the creditCardValidator object complete, it's time to use the resource:

完成creditCardValidator对象后,就可以使用该资源了:


if(!creditCardValidator.validate(document.id("creditCardField"))) {
	alert("Invalid credit card!");
}


There you have it:  simple credit card validation with code taken from the Dojo Toolkit.  Problem solved!

在那里,您可以使用来自Dojo Toolkit的代码进行简单的信用卡验证。 问题解决了!

翻译自: https://davidwalsh.name/validate-credit-cards

javascript验证

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值