`

Credit Card 的工具类

    博客分类:
  • java
阅读更多

这是一个非常有用的工具类用于验证credit card, 是apache alidation的工具类。 

 

http://www.apache.org/licenses/LICENSE-2.0
 

package org.apache.commons.validator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.validator.util.Flags;

/**
 * <p>Perform credit card validations.</p>
 * <p>
 * By default, all supported card types are allowed.  You can specify which
 * cards should pass validation by configuring the validation options.  For
 * example,<br/><code>CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.AMEX + CreditCardValidator.VISA);</code>
 * configures the validator to only pass American Express and Visa cards.
 * If a card type is not directly supported by this class, you can implement
 * the CreditCardType interface and pass an instance into the
 * <code>addAllowedCardType</code> method.
 * </p>
 * For a similar implementation in Perl, reference Sean M. Burke's
 * <a href="http://www.speech.cs.cmu.edu/~sburke/pub/luhn_lib.html">script</a>.
 * More information is also available
 * <a href="http://www.merriampark.com/anatomycc.htm">here</a>.
 *
 * @since Validator 1.1
 */
public class CreditCardValidator {

    /**
     * Option specifying that no cards are allowed.  This is useful if
     * you want only custom card types to validate so you turn off the
     * default cards with this option.
     * <br/>
     * <pre>
     * CreditCardValidator v = new CreditCardValidator(CreditCardValidator.NONE);
     * v.addAllowedCardType(customType);
     * v.isValid(aCardNumber);
     * </pre>
     * @since Validator 1.1.2
     */
    public static final int NONE = 0;

    /**
     * Option specifying that American Express cards are allowed.
     */
    public static final int AMEX = 1 << 0;

    /**
     * Option specifying that Visa cards are allowed.
     */
    public static final int VISA = 1 << 1;

    /**
     * Option specifying that Mastercard cards are allowed.
     */
    public static final int MASTERCARD = 1 << 2;

    /**
     * Option specifying that Discover cards are allowed.
     */
    public static final int DISCOVER = 1 << 3;
   
    /**
     * The CreditCardTypes that are allowed to pass validation.
     */
    private Collection cardTypes = new ArrayList();

    /**
     * Create a new CreditCardValidator with default options.
     */
    public CreditCardValidator() {
        this(AMEX + VISA + MASTERCARD + DISCOVER);
    }

    /**
     * Create a new CreditCardValidator with the specified options.
     * @param options Pass in
     * CreditCardValidator.VISA + CreditCardValidator.AMEX to specify that
     * those are the only valid card types.
     */
    public CreditCardValidator(int options) {
        super();

        Flags f = new Flags(options);
        if (f.isOn(VISA)) {
            this.cardTypes.add(new Visa());
        }

        if (f.isOn(AMEX)) {
            this.cardTypes.add(new Amex());
        }

        if (f.isOn(MASTERCARD)) {
            this.cardTypes.add(new Mastercard());
        }

        if (f.isOn(DISCOVER)) {
            this.cardTypes.add(new Discover());
        }
    }

    /**
     * Checks if the field is a valid credit card number.
     * @param card The card number to validate.
     */
    public boolean isValid(String card) {
        if ((card == null) || (card.length() < 13) || (card.length() > 19)) {
            return false;
        }

        if (!this.luhnCheck(card)) {
            return false;
        }
       
        Iterator types = this.cardTypes.iterator();
        while (types.hasNext()) {
            CreditCardType type = (CreditCardType) types.next();
            if (type.matches(card)) {
                return true;
            }
        }

        return false;
    }
   
    /**
     * Add an allowed CreditCardType that participates in the card
     * validation algorithm.
     * @param type The type that is now allowed to pass validation.
     * @since Validator 1.1.2
     */
    public void addAllowedCardType(CreditCardType type){
        this.cardTypes.add(type);
    }

    /**
     * Checks for a valid credit card number.
     * @param cardNumber Credit Card Number.
     */
    protected boolean luhnCheck(String cardNumber) {
        // number must be validated as 0..9 numeric first!!
        int digits = cardNumber.length();
        int oddOrEven = digits & 1;
        long sum = 0;
        for (int count = 0; count < digits; count++) {
            int digit = 0;
            try {
                digit = Integer.parseInt(cardNumber.charAt(count) + "");
            } catch(NumberFormatException e) {
                return false;
            }

            if (((count & 1) ^ oddOrEven) == 0) { // not
                digit *= 2;
                if (digit > 9) {
                    digit -= 9;
                }
            }
            sum += digit;
        }

        return (sum == 0) ? false : (sum % 10 == 0);
    }

    /**
     * Checks for a valid credit card number.
     * @param card Credit Card Number.
     * @deprecated This will be removed in a future release.
     */
    protected boolean isValidPrefix(String card) {

        if (card.length() < 13) {
            return false;
        }
       
        return new Visa().matches(card)
            || new Amex().matches(card)
            || new Mastercard().matches(card)
            || new Discover().matches(card);
    }
   
    /**
     * CreditCardType implementations define how validation is performed
     * for one type/brand of credit card.
     * @since Validator 1.1.2
     */
    public interface CreditCardType {
       
        /**
         * Returns true if the card number matches this type of credit
         * card.  Note that this method is <strong>not</strong> responsible
         * for analyzing the general form of the card number because
         * <code>CreditCardValidator</code> performs those checks before
         * calling this method.  It is generally only required to valid the
         * length and prefix of the number to determine if it's the correct
         * type.
         * @param card The card number, never null.
         * @return true if the number matches.
         */
        boolean matches(String card);
       
    }
   
    private class Visa implements CreditCardType {
        private static final String PREFIX = "4";
        public boolean matches(String card) {
            return (
                card.substring(0, 1).equals(PREFIX)
                    && (card.length() == 13 || card.length() == 16));
        }
    }
   
    private class Amex implements CreditCardType {
        private static final String PREFIX = "34,37,";
        public boolean matches(String card) {
            String prefix2 = card.substring(0, 2) + ",";
            return ((PREFIX.indexOf(prefix2) != -1) && (card.length() == 15));
        }
    }
   
    private class Discover implements CreditCardType {
        private static final String PREFIX = "6011";
        public boolean matches(String card) {
            return (card.substring(0, 4).equals(PREFIX) && (card.length() == 16));
        }
    }
   
    private class Mastercard implements CreditCardType {
        private static final String PREFIX = "51,52,53,54,55,";
        public boolean matches(String card) {
            String prefix2 = card.substring(0, 2) + ",";
            return ((PREFIX.indexOf(prefix2) != -1) && (card.length() == 16));
        }
    }

}

分享到:
评论

相关推荐

    creditcard.zip

    本资料包“creditcard.zip”聚焦于这个话题,包含了一个名为“creditcard.csv”的CSV数据集以及一个名为“sss.txt”的文本文件。我们将深入探讨信用卡欺诈检测这一领域,以及如何利用这些数据进行分析。 一、信用卡...

    creditcard:信用卡欺诈检测数据集-数据集

    《信用卡欺诈检测:深入理解creditcard数据集》 在当今数字化的世界中,信用卡交易已经成为日常生活中不可或缺的一部分。然而,随之而来的欺诈行为也日益猖獗,对个人和金融机构造成重大损失。为了对抗这一威胁,...

    CreditCardValidator

    在IT行业中,数据安全与支付验证是至关重要的环节,而CreditCardValidator正是这样一款工具,用于验证信用卡号的合法性。它基于Java编程语言,提供了高效、准确的信用卡号校验功能,确保了在线交易的安全性。本文将...

    Flutter-Credit-Card-Input-Form.zip

    【标题】"Flutter-Credit-Card-Input-Form.zip" 提供的是一个使用 Flutter 开发的信用卡输入表单,适用于移动应用开发,特别是在处理金融交易或支付相关功能时。Flutter 是 Google 推出的开源 UI 工具包,用于构建高...

    Credit card icon

    "Credit card icon"通常是指一种图形符号,代表不同的信用卡品牌,如Visa、Mastercard、American Express等,用于识别和表示接受特定信用卡支付的商家或服务。这些图标简洁而直观,旨在方便用户快速识别并进行交易。...

    Laravel开发-credit-card

    本项目"credit-card"专注于实现对信用卡号、有效期(expiration date)以及CVC(Card Verification Code)的验证功能。以下是对这个项目相关知识点的详细讲解: 1. **Laravel框架**:Laravel是一款基于PHP的开源Web...

    Credit_Wizard_visa.card.v1.1_credit_

    "Credit Wizard visa.card.v1.1_credit_",这款应用以智能化的方式,帮助用户更好地掌控自己的信用卡消费和还款,从而提升财务管理的效率。 "Credit Wizard v1.1" 是一个专为 Visa 卡持卡人设计的信用卡管理工具。...

    Laravel开发-laravel-credit-card-validator

    `laravel-credit-card-validator`项目就是一个专为此目的而设计的工具,它可以帮助开发者高效且安全地验证用户输入的信用卡信息。下面我们将深入探讨这个项目以及在Laravel中进行信用卡验证的相关知识点。 1. **...

    credit_card_default-数据集

    总结,"credit_card_default"数据集是研究信用卡违约风险的理想工具,通过对数据的深入分析,我们可以提高金融机构的风险管控能力,同时也可以推动信用评估技术的发展。在实际应用中,结合业务理解和算法优化,这个...

    刘渝_CreditCard competition.docx1

    在Python中,scikit-learn库提供了便利的工具来执行这些步骤。通过比较不同模型的性能,可以选择最合适的模型来解决信用卡申请批准的问题。在实际应用中,可能还需要考虑其他因素,如模型的复杂性、训练时间、可解释...

    Laravel开发-php-credit-card-validator-plus

    在实现`Credit-Card-Validator-Plus`时,你需要创建一个服务类,该类包含以下方法: - `validateCardNumber($number)`: 使用正则表达式检查信用卡号的格式,确保它符合特定品牌的格式。 - `validateLuhn($number)`:...

    Credit-Card-Number-Validator

    - 类设计:`CreditCard`类可能包含私有字段(如`cardNumber`),公开的getter和setter方法,以及验证信用卡号的方法。 - 构造函数:可能有一个构造函数用于初始化`CreditCard`对象,接受信用卡号作为参数。 5. **...

    Argosz\'s Credit Card Checker-开源

    import com.argosz.creditcard.CreditCardChecker; public class Main { public static void main(String[] args) { String cardNumber = "4111111111111111"; // 一个示例的Visa卡号 if (CreditCardChecker.is...

    creditcards-types:信用卡的卡类型定义和方法

    这个库为动力,是一种用于分析/格式化/验证卡数据的高级工具。 该存储库侧重于和。 卡类型主要由静态值和正则表达式表示。 卡类型 签证 万事达 美国运通 大来俱乐部 发现 杰西博 银联 大师 Forforugsforeningen ...

    credit card-api:带有TDD,Spring Boot,Embedded MongoDB,HATEOAS和Spring REST Docs的示例

    信用卡API示例 Example with Integration Tests, Spring Boot, Embedded MongoDB, HATEOAS, Spring REST Docs and AsciiDoctor The Credit Card API uses CodeShip and Heroku for Continuous Delivery. ...工具类

    creditcard-list-order-web-service

    总结来说,"creditcard-list-order-web-service"项目是利用Java Web技术实现的一个实用工具,它通过读取CSV文件,对信用卡信息进行排序,提供了一种便捷的方式来管理大量的信用卡数据。用户只需要在`web.xml`中配置...

    creditcard.craft-plugin:为“验证”教程系列创建的示例Craft插件

    在Craft的插件结构中,`creditcard.craft-plugin-master`可能包含`Plugin.php`文件,这是Craft插件的核心,定义了插件类和元数据。还有可能包含`services`目录,其中的类负责具体的业务逻辑,如验证函数。 为了提高...

    javacard源码-ufr-apdu-credit_card_reader-examples-java:uFRapdu示例的Java源代码,

    7. **测试与调试**:了解如何在Java Card模拟器或真实卡片上进行测试,以及如何利用JCIDE等工具进行调试。 通过深入研究这个开源项目,你不仅可以提升Java Card开发技能,还能了解实际的信用卡读取应用案例,这对于...

Global site tag (gtag.js) - Google Analytics