什么是 creditcards?
creditcards 是一个 JavaScript 库,用于验证和格式化信用卡号码、过期日期、CVV 码以及卡片类型。它可以在前端和后端使用,支持多种卡片类型,包括 Visa、Mastercard、Amex、Discover 等。
安装 creditcards
你可以通过 npm 安装 creditcards:
npm install creditcards --save
验证信用卡号码
creditcards 提供了一个 card.isValid
方法,用于验证信用卡号码是否有效。它支持多种信用卡类型,可以通过可选的 type
参数进行指定。例如:
const card = require('creditcards').card; console.log(card.isValid('4111-1111-1111-1111')); // true console.log(card.isValid('4111-1111-1111-1112')); // false console.log(card.isValid('3400-0000-0000-009')); // true, type: 'Amex' console.log(card.isValid('6011-0000-0000-0004', 'Discover')); // true
格式化信用卡号码
creditcards 提供了一个 card.format
方法,用于格式化信用卡号码。例如:
console.log(card.format('4111-1111-1111-1111')); // "4111 1111 1111 1111" console.log(card.format('3400-0000-0000-009', 'Amex')); // "3400 000000 00009"
验证过期日期和 CVV 码
creditcards 提供了 expiration
和 cvv
对象,分别用于验证过期日期和 CVV 码。例如:
const expiration = require('creditcards').expiration; const cvv = require('creditcards').cvv; console.log(expiration.isPast('01/2021')); // true console.log(expiration.parse('01/2022')); // { month: 1, year: 2022 } console.log(cvv.isValid('123', 'Amex')); // true
总结
creditcards 是一个方便的 JavaScript 库,用于验证和格式化信用卡信息。通过上述方法,你可以轻松地验证和格式化信用卡号码、过期日期、CVV 码以及卡片类型。希望这篇文章能够帮助你更好地使用 creditcards。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/5eedb474b5cbfe1ea06112a3