Wednesday, November 13, 2013

Validate credit card and get card type by java code

import org.apache.commons.validator.GenericValidator

def getCreditCardType(String cardNumber) throws AutobillException {
    cardNumber = "" + cardNumber;
    cardNumber = cardNumber.trim();
    cardNumber = cardNumber.replaceAll("\\D+", "");
    if(!GenericValidator.isCreditCard(cardNumber)) {
        throw new InvalidPropertyException("cardNumber");
    }
    if(cardNumber.matches(("^4[0-9]{12}(?:[0-9]{3})?\$"))) {
        return "VISA";
    } else if(cardNumber.matches(("^5[1-5][0-9]{14}\$"))) {
        return "MASTERCARD";
    } else if(cardNumber.matches(("^3[47][0-9]{13}\$"))) {
        return "AMEX";
    } else if(cardNumber.matches(("^3(?:0[0-5]|[68][0-9])[0-9]{11}\$"))) {
        return "DINERS";
    } else if(cardNumber.matches(("^6(?:011|5[0-9]{2})[0-9]{12}\$"))) {
        return "DISCOVER";
    } else if(cardNumber.matches(("^(?:2131|1800|35\\d{3})\\d{11}\$"))) {
        return "JCB";
    }
    return null;
}

No comments:

Post a Comment