I am wondering how I can style one input field (type = text) to display with spaces and a slash between numbers, like this:
I know how to constrain the input to digits and perform validation. That's not what I'm asking. I'm wondering about the actual display. Can you use CSS to do this somehow, splitting the first two MM digits from the last two YY digits?
I want the user to be able to type 4 digits only and have it display as: MM / YY
(Different question from How to format credit card input fields and expiry date. That question focuses on validation.)
As our benchmark reveals that only 10% of sites format expiration date fields to match what’s actually printed on the card, it’s worth looking at some examples of how the other 90% of sites format expiration date fields, in order of most problematic to least. 1) Month Name, Four-Digit Year.
This will still allow users to use the keyboard to input the expiration month and to select the digits as they see them printed on their card. The expiration date drop-downs can be improved even more by including a forward slash to separate the month and year fields, as well as by adding labels beneath each field (i.e., “Month”, “Year” ).
Walmart uses the ISO standard format for credit card expiration date, “MM / YY”. To perfect this implementation labels should also be provided for the “Month” and “Year” fields.
A minority of users, however, will encounter payment validation errors because they’ve inputted the card’s expiration date incorrectly. This can lead to abandonments, depending on the error-recovery experience.
You can accomplish this using two inputs fields, removing the border of the input fields, adding a border to a wrapper element to appear as one input and a place /
in between like so. - jsFiddle Demo
HTML
<span class="expiration">
<input type="text" name="month" placeholder="MM" maxlength="2" size="2" />
<span>/</span>
<input type="text" name="year" placeholder="YY" maxlength="2" size="2" />
</span>
CSS
.expiration {
border: 1px solid #bbbbbb;
}
.expiration input {
border: 0;
}
Result
This is just the CSS needed to demonstrate the idea, of course you can style it however you'd like.
I used <span>
s because they are inline elements, as are input fields.
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.
This is my solution using Regex.
const expdate = '0421';
const expDateFormatter = expdate.replace(/\//g, "").substring(0, 2) +
(expdate.length > 2 ? '/' : '') +
expdate.replace(/\//g, "").substring(2, 4);
console.log(expDateFormatter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With