Return to Snippet

Revision: 38517
at January 4, 2011 12:01 by Activetuts


Initial Code
public function validateCardNumber(ccNumber:String):Boolean
{
    var americanExpress:RegExp  = /^(34|37) ([0-9]{13})$/x;
    var dinnersClub:RegExp      = /^(30[0-5]) ([0-9]{13})$/x;
    var masterCard:RegExp       = /^(5[1-5]) ([0-9]{14})$/x;
    var visa:RegExp             = /^4 ([0-9]{12} | [0-9]{15})$/x;
    var valid:Boolean;
    ccNumber = ccNumber.match(/\d/g).join('');
 
    if (americanExpress.test(ccNumber) || dinnersClub.test(ccNumber) ||
        masterCard.test(ccNumber) || visa.test(ccNumber))
        valid = true;
 
    return valid && luhnChecksum(ccNumber);
}

public function luhnChecksum(number:String):Boolean
{
    var digits:Array = number.split('');
    var start:uint = (number.length % 2 == 0) ? 0:1;
    var sum:int;
 
    while (start < digits.length)
    {
        digits[start] = uint(digits[start]) * 2;
        start += 2;
    }
 
    digits = digits.join('').split('');
 
    for (var i:uint = 0; i < digits.length; i++)
    {
        sum += uint(digits[i]);
    }
    return (sum % 10 == 0);
}

Initial URL
http://active.tutsplus.com/tutorials/actionscript/validating-various-input-data-in-flash/

Initial Description
From the tutorial, Validating Various Input Data in Flash (http://active.tutsplus.com/tutorials/actionscript/validating-various-input-data-in-flash/)

Initial Title
Validate Card Number with RegExp

Initial Tags
regexp, validation

Initial Language
ActionScript 3