How to Format Credit Card Expiry Date in Mm/Yy When Entered by User

how to format credit card expiry date in mm/yy when entered by user

First set the max amount of characters of the EditText to 5, like this:

android:maxLength="5"

And set as numbers editText

android:inputType="number"

Then add an onEditTextChangedListener to the EditText to detect if the amount of characters is changed to two and did not change from three to two and remove "/" if a number before "/" is removed:

edit_text.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {}

override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}

override fun onTextChanged(p0: CharSequence?, start: Int, removed: Int, added: Int) {
if (start == 1 && start+added == 2 && p0?.contains('/') == false) {
edit_text.setText(p0.toString() + "/")
} else if (start == 3 && start-removed == 2 && p0?.contains('/') == true) {
edit_text.setText(p0.toString().replace("/", ""))
}
}
})

formatting expiry date in mm/yy format

See my comment above to understand your issue. You might use this to verify the user input with your textwatcher:

SimpleDateFormat formatter = 
new SimpleDateFormat("MM/yy", Locale.GERMANY);
Calendar expiryDateDate = Calendar.getInstance();
try {
expiryDateDate.setTime(formatter.parse(mExpiryDate.getText().toString()));
} catch (ParseException e) {
//not valid
}
// expiryDateDate has a valid date from the user

So in complete it would be:

String lastInput ="";

@Override
public void afterTextChanged(Editable s) {
String input = s.toString();
SimpleDateFormat formatter = new SimpleDateFormat("MM/yy", Locale.GERMANY);
Calendar expiryDateDate = Calendar.getInstance();
try {
expiryDateDate.setTime(formatter.parse(input));
} catch (ParseException e) {
if (s.length() == 2 && !lastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString() + "/");
}
}else if (s.length() == 2 && lastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString().subStr(0,1);
}
}
lastInput = mExpiryDate.getText().toString();
//because not valid so code exits here
return;
}
// expiryDateDate has a valid date from the user
// Do something with expiryDateDate here
}

Finally the complete solution:

String input = s.toString();
SimpleDateFormat formatter = new SimpleDateFormat("MM/yy", Locale.GERMANY);
Calendar expiryDateDate = Calendar.getInstance();
try {
expiryDateDate.setTime(formatter.parse(input));
} catch (ParseException e) {

} catch (java.text.ParseException e) {
if (s.length() == 2 && !mLastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString() + "/");
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
}
}else if (s.length() == 2 && mLastInput.endsWith("/")) {
int month = Integer.parseInt(input);
if (month <= 12) {
mExpiryDate.setText(mExpiryDate.getText().toString().substring(0,1));
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
} else {
mExpiryDate.setText("");
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
Toast.makeText(getApplicationContext(), "Enter a valid month", Toast.LENGTH_LONG).show();
}
} else if (s.length() == 1){
int month = Integer.parseInt(input);
if (month > 1) {
mExpiryDate.setText("0" + mExpiryDate.getText().toString() + "/");
mExpiryDate.setSelection(mExpiryDate.getText().toString().length());
}
}
else {

}
mLastInput = mExpiryDate.getText().toString();
return;

Validate credit card date format MM/yy to Valid Month and Year . Asp.net core

The code is correct. When parsing two digit year you have to adjust the Calendar.TwoDigitYearMax.

The default calendar goes from 1930 to 2029 so, when parsing year 30, it assumes 1930.

Fix it using something like:

CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.LCID);
ci.Calendar.TwoDigitYearMax = 2099; // the end year, so it goes from 2000 to 2099.
var result = DateTime.ParseExact("12/30", "MM/yy", ci);

Format credit card date MM/yy to MM/dd/yyyy

You can use java.time.YearMonth class, which contains a method that returns the last day of the respective month (and also takes care of leap years):

public static boolean dateHasExpired(String dateInput) {
LocalDate today = LocalDate.now();
LocalDate dateParsed = null;

if (dateInput.contains("/")) {
// parse credit card expiration date
YearMonth ym = YearMonth.parse(dateInput, DateTimeFormatter.ofPattern("MM/yy"));
// get last day of month (taking care of leap years)
dateParsed = ym.atEndOfMonth();
} else {
// parse funding expiration date
dateParsed = LocalDate.parse(dateInput, DateTimeFormatter.ofPattern("yyyyMMdd"));
}

// expired if today is equals or after dateParsed
return ! today.isBefore(dateParsed);
}

With this code (considering that today is May 02, 2017):

System.out.println(dateHasExpired("04/17")); // true
System.out.println(dateHasExpired("05/17")); // false
System.out.println(dateHasExpired("06/17")); // false
System.out.println(dateHasExpired("20170501")); //true
System.out.println(dateHasExpired("20170502")); // true
System.out.println(dateHasExpired("20170503")); // false

Note that atEndOfMonth() method takes care of leap years, so these will also work:

System.out.println(dateHasExpired("02/15"));
System.out.println(dateHasExpired("02/16"));

I've added a System.out.println(dateParsed); in dateHasExpired method, just to check if the date is being parsed correctly. And the output for the dates above are (respectively):

2015-02-28
2016-02-29

And dateHasExpired returns true for both, as expected.

How to style a credit card expiration date input field to include spaces and forward slash?

Read first few characters and save them to the variable. then read last characters, and write them into other variable... Then concatenate with the space between them.

How can I get last characters of a string using JavaScript

Retrieve first 2 characters of this.title attribute, and call corresponding id

Or, have 2 fields and style them with CSS to look like a single field.

How would you automatically add '/' to a date in mmyyyy format with javascript?

This should update it in real time. Remember to validate the input properly.

function addSlashes (element) {     let ele = document.getElementById(element.id);    ele = ele.value.split('/').join('');    // Remove slash (/) if mistakenly entered.    if(ele.length < 4 && ele.length > 0){        let finalVal = ele.match(/.{1,2}/g).join('/');
document.getElementById(element.id).value = finalVal; }}
<input id="dateInput" onkeyup="addSlashes(this)" maxlength=7>

validate the credit card expiry date using java?

Playing devil's advocate...

boolean validateCardExpiryDate(String expiryDate) {
return expiryDate.matches("(?:0[1-9]|1[0-2])/[0-9]{2}");
}

which translates as:

  • a non-capturing group ( What is a non-capturing group? What does a question mark followed by a colon (?:) mean? ) of: 0 followed by 1-9, or 1 followed by 0-2
  • followed by "/"
  • followed by 0-9, twice.

...so this version requires zero-padded months (01 - 12). Add a ? after the first 0 to prevent this.



Related Topics



Leave a reply



Submit