how to format credit card expiry date in mm/yy when entered by user
android:maxLength="5"
And set as phone to editText so that it can display "/"
android:inputType="phone"
on the textWatcher do this .... I will validate later for the correct mm/yy month year to avoid users input data like 55/66 max should be 12/31 but it should be validated for months with less or 30 days...
@Override
public void afterTextChanged(Editable editable) {
if (editable.length() > 0 && (editable.length() % 3) == 0) {
final char c = editable.charAt(editable.length() - 1);
if ('/' == c) {
editable.delete(editable.length() - 1, editable.length());
}
}
if (editable.length() > 0 && (editable.length() % 3) == 0) {
char c = editable.charAt(editable.length() - 1);
if (Character.isDigit(c) && TextUtils.split(editable.toString(), String.valueOf("/")).length <= 2) {
editable.insert(editable.length() - 1, String.valueOf("/"));
}
}
}
I just implement a method like Uber credit card date format with auto check, autocomplete, auto move to CVV edittext.
<EditText
android:id="@+id/credit_card_expire_et"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/activity_horizontal_margin"
android:layout_weight="1"
android:hint="MM/YY"
android:inputType="number"
android:maxLength="5"
android:maxLines="1" />
<EditText
android:id="@+id/credit_card_cvv_et"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_weight="1"
android:hint="CVV"
android:inputType="number"
android:maxLength="3"
android:maxLines="1" />
.
@BindView(R.id.credit_card_expire_et)
EditText creditExpireEt;
@BindView(R.id.credit_card_cvv_et)
EditText creditCVVEt;
@OnTextChanged(value = R.id.credit_card_expire_et, callback = BEFORE_TEXT_CHANGED)
void beforeExpireEtChanged() {
previousLength = creditExpireEt.getText().toString().length();
}
@OnTextChanged(R.id.credit_card_expire_et)
void autoFixAndMoveToNext() {
int length = creditExpireEt.getText().toString().trim().length();
if (previousLength <= length && length < 3) {
int month = Integer.parseInt(creditExpireEt.getText().toString());
if (length == 1 && month >= 2) {
String autoFixStr = "0" + month + "/";
creditExpireEt.setText(autoFixStr);
creditExpireEt.setSelection(3);
} else if (length == 2 && month <= 12) {
String autoFixStr = creditExpireEt.getText().toString() + "/";
creditExpireEt.setText(autoFixStr);
creditExpireEt.setSelection(3);
} else if (length ==2 && month > 12) {
creditExpireEt.setText("1");
creditExpireEt.setSelection(1);
}
} else if (length == 5) {
creditCVVEt.requestFocus(); // auto move to next edittext
}
}