-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCreditCardTextWatcher.java
More file actions
78 lines (61 loc) · 2.3 KB
/
CreditCardTextWatcher.java
File metadata and controls
78 lines (61 loc) · 2.3 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.flutterwave.raveandroid.card;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import com.flutterwave.raveandroid.R;
import java.util.regex.Pattern;
/**
* Created by hamzafetuga on 24/07/2017.
*/
class CreditCardTextWatcher implements TextWatcher {
private static final char space = ' ';
private final int mDefaultDrawableResId = R.drawable.ic_credit_card;
private int mCurrentDrawableResId = 0;
private Drawable mCurrentDrawable;
String lastFormattedText;
private SparseArray<Pattern> mCCPatterns = null;
CreditCardTextWatcher() {
init();
}
private void init() {
if (mCCPatterns == null) {
mCCPatterns = new SparseArray<>();
// With spaces for credit card masking
mCCPatterns.put(R.drawable.ic_visa, Pattern.compile(
"^4[0-9]{2,12}(?:[0-9]{3})?$"));
mCCPatterns.put(R.drawable.ic_master_card, Pattern.compile(
"^5[1-5][0-9]{1,14}$"));
mCCPatterns.put(R.drawable.ic_american_express, Pattern.compile(
"^3[47][0-9]{1,13}$"));
///^([506]{3})([0-9]{1,16})$/
mCCPatterns.put(R.drawable.ic_verve_logo, Pattern.compile(
"^([506]{3})([0-9]{1,16})$"
));
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0 && (s.length() % 5) == 0) {
final char c = s.charAt(s.length() - 1);
if (space == c) {
s.delete(s.length() - 1, s.length());
}
}
// Insert char where needed.
if (s.length() > 0 && (s.length() % 5) == 0) {
char c = s.charAt(s.length() - 1);
// Only if its a digit where there should be a space we insert a space
if (Character.isDigit(c) && TextUtils.split(s.toString(), String.valueOf(space)).length <= 3) {
s.insert(s.length() - 1, String.valueOf(space));
}
}
}
}