Vue.js Input Mask Attempt
HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<label>Credit Card</label>
<cc-input></cc-input>
</div>
CSS
input {
font-size: 22px;
padding: .25em .5em;
margin-bottom: 2em;
}
label {
font-size: 18px;
display: block;
}
Babel + JSX
function maskInput(mask, oldValue, newValue, newCursorPosition) {
let subtractive = newValue.length < oldValue.length
let updatedCursorPosition = newCursorPosition
let updatedValue = ''
for (let i = 0; updatedValue.length < mask.length && i < newValue.length; i++) {
let char = newValue[i].toUpperCase()
let allowedCharacters = mask[updatedValue.length].split('')
// If character is allowed, include it
if (allowedCharacters.includes(char)) {
updatedValue = updatedValue + char
// If it's not allowed, but the mask forces a specific character for this position,
// insert the forced character and match the current character against the next
// slot instead.
} else if (allowedCharacters.length === 1) {
if (updatedCursorPosition > updatedValue.length) {
updatedCursorPosition = updatedCursorPosition + 1
}
updatedValue = updatedValue + allowedCharacters[0]
i = i - 1
// If we skipped the character entirely, shift the cursor position back one to
// account for the removed character.
} else if (i < newCursorPosition) {
updatedCursorPosition = updatedCursorPosition - 1
}
}
updatedCursorPosition = Math.min(updatedCursorPosition, updatedValue.length)
// If cursor is at end, add guessable characters if additive,
// or subtract guessable characters if subtractive
if (updatedCursorPosition == updatedValue.length) {
if (subtractive) {
for (let i = updatedValue.length - 1; i >= 0; i--) {
let allowedCharacters = mask[i].split('')
if (allowedCharacters.length == 1) {
updatedValue = updatedValue.slice(0, -1)
updatedCursorPosition = updatedCursorPosition - 1
} else {
break
}
}
} else {
for (let i = updatedValue.length; i < mask.length; i++) {
let allowedCharacters = mask[i].split('')
if (allowedCharacters.length == 1) {
updatedValue = updatedValue +...