1
14
15 package com.liferay.util;
16
17 import com.liferay.portal.kernel.util.StringBundler;
18 import com.liferay.portal.kernel.util.StringPool;
19 import com.liferay.portal.kernel.util.StringUtil;
20 import com.liferay.portal.kernel.util.Validator;
21
22
27 public class CreditCard {
28
29 public static String hide(String number) {
30 return hide(number, StringPool.STAR);
31 }
32
33 public static String hide(String number, String x) {
34 if (number == null) {
35 return number;
36 }
37
38 int numberLen = number.length();
39
40 if (numberLen > 4) {
41 StringBundler sb = new StringBundler(numberLen - 3);
42
43 for (int i = 0; i < numberLen - 4; i++) {
44 sb.append(x);
45 }
46
47 sb.append(number.substring(numberLen - 4, numberLen));
48
49 number = sb.toString();
50 }
51
52 return number;
53 }
54
55 public static boolean isValid(String number, String type) {
56 number = StringUtil.extractDigits(number);
57
58 if (type.equals("visa")) {
59 if (!number.startsWith("4")) {
60 return false;
61 }
62
63 if (number.length() != 13 &&
64 number.length() != 16) {
65
66 return false;
67 }
68 }
69 else if (type.equals("mastercard")) {
70 if (!number.startsWith("51") &&
71 !number.startsWith("52") &&
72 !number.startsWith("53") &&
73 !number.startsWith("54") &&
74 !number.startsWith("55")) {
75
76 return false;
77 }
78
79 if (number.length() != 16) {
80 return false;
81 }
82 }
83 else if (type.equals("discover")) {
84 if (!number.startsWith("6011")) {
85
86 return false;
87 }
88
89 if (number.length() != 16) {
90 return false;
91 }
92 }
93 else if (type.equals("amex")) {
94 if (!number.startsWith("34") &&
95 !number.startsWith("35") &&
96 !number.startsWith("36") &&
97 !number.startsWith("37")) {
98
99 return false;
100 }
101
102 if (number.length() != 15) {
103 return false;
104 }
105 }
106
107 return Validator.isLUHN(number);
108 }
109
110 }