Credit card verification using JavaScript

Source: Internet
Author: User

Credit card verification using JavaScript

Here, the JavaScript version of the credit card verification code uses the Luhn Algorithm

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

Function isValidCreditCard (type, ccnum ){

If (type = "Visa "){

// Visa: length 16, prefix 4, dashes optional.

Var re =/^ 4 \ d {3 }-? \ D {4 }-? \ D {4 }-? \ D {4} $ /;

} Else if (type = "MC "){

// Mastercard: length 16, prefix 51-55, dashes optional.

Var re =/^ 5 [1-5] \ d {2 }-? \ D {4 }-? \ D {4 }-? \ D {4} $ /;

} Else if (type = "Disc "){

// Discover: length 16, prefix 6011, dashes optional.

Var re =/^ 6011 -? \ D {4 }-? \ D {4 }-? \ D {4} $ /;

} Else if (type = "AmEx "){

// American Express: length 15, prefix 34 or 37.

Var re =/^ 3 [4, 7] \ d {13} $ /;

} Else if (type = "Diners "){

// Diners: length 14, prefix 30, 36, or 38.

Var re =/^ 3 [0, 6, 8] \ d {12} $ /;

}

If (! Re. test (ccnum) return false;

// Remove all dashes for the checksum

// Checks to eliminate negative numbers

Ccnum = ccnum. split ("-"). join ("");

// Checksum ("Mod 10 ")

// Add even digits in even length strings

// Or odd digits in odd length strings.

Var checksum = 0;

For (var I = (2-(ccnum. length % 2); I <= ccnum. length; I + = 2 ){

Checksum + = parseInt (ccnum. charAt (I-1 ));

}

// Analyze odd digits in even length strings

// Or even digits in odd length strings.

For (var I = (ccnum. length % 2) + 1; I <ccnum. length; I + = 2 ){

Var digit = parseInt (ccnum. charAt (I-1) * 2;

If (digit <10) {checksum + = digit ;}

Else {checksum + = (digit-9 );}

}

If (checksum % 10) = 0) return true; else return false;

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.