Validate Card Number with RegExp


/ Published in: ActionScript 3
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. public function validateCardNumber(ccNumber:String):Boolean
  2. {
  3. var americanExpress:RegExp = /^(34|37) ([0-9]{13})$/x;
  4. var dinnersClub:RegExp = /^(30[0-5]) ([0-9]{13})$/x;
  5. var masterCard:RegExp = /^(5[1-5]) ([0-9]{14})$/x;
  6. var visa:RegExp = /^4 ([0-9]{12} | [0-9]{15})$/x;
  7. var valid:Boolean;
  8. ccNumber = ccNumber.match(/\d/g).join('');
  9.  
  10. if (americanExpress.test(ccNumber) || dinnersClub.test(ccNumber) ||
  11. masterCard.test(ccNumber) || visa.test(ccNumber))
  12. valid = true;
  13.  
  14. return valid && luhnChecksum(ccNumber);
  15. }
  16.  
  17. public function luhnChecksum(number:String):Boolean
  18. {
  19. var digits:Array = number.split('');
  20. var start:uint = (number.length % 2 == 0) ? 0:1;
  21. var sum:int;
  22.  
  23. while (start < digits.length)
  24. {
  25. digits[start] = uint(digits[start]) * 2;
  26. start += 2;
  27. }
  28.  
  29. digits = digits.join('').split('');
  30.  
  31. for (var i:uint = 0; i < digits.length; i++)
  32. {
  33. sum += uint(digits[i]);
  34. }
  35. return (sum % 10 == 0);
  36. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.