Skip to content

Instantly share code, notes, and snippets.

@niorad
Created March 8, 2018 13:50
Show Gist options
  • Save niorad/3e92a403a2968c406bf0ee28a5c96079 to your computer and use it in GitHub Desktop.
Save niorad/3e92a403a2968c406bf0ee28a5c96079 to your computer and use it in GitHub Desktop.
Automatic grouping of Iban-Numbers, supporting Backspace- and Del-Keys.
// <input type="text" id="iban">
document.getElementById('iban').addEventListener('input', function (e) {
var target = e.target, position = target.selectionEnd, length = target.value.length;
target.value = target.value.replace(/[^\dA-Za-z]/g, '').replace(/(.{4})/g, '$1 ').trim();
if(e.inputType === 'deleteContentForward') {
target.selectionEnd = position += ((target.value.charAt(position) === ' ') ? 1 : 0);
} else {
target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
if(target.selectionEnd % 5 === 0) {
if( target.value.length % 5 !== 1 ) {
target.selectionEnd++;
target.selectionStart = target.selectionEnd;
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment