Skip to content

Instantly share code, notes, and snippets.

@MrMooky
Created February 24, 2021 15:41
Show Gist options
  • Save MrMooky/33c9e721d1d55c871d81df26413dfda9 to your computer and use it in GitHub Desktop.
Save MrMooky/33c9e721d1d55c871d81df26413dfda9 to your computer and use it in GitHub Desktop.
<input type='tel' data-filter='[0-9|+]*' placeholder='123+456'>
<input type='tel' data-filter='(\+|(\+[1-9])?[0-9]*)' placeholder='+10123'>
<input type='text' data-filter='([A-Z]?|[A-Z][a-z]*)' placeholder='Abcdefg'>
<input type='text' data-filter='([A-Z]{0,3}|[A-Z]{3}[0-9]*)' placeholder='ABC123'>
---
// Apply filter to all inputs with data-filter:
let inputs = document.querySelectorAll('input[data-filter]');
for (let input of inputs) {
let state = {
value: input.value,
start: input.selectionStart,
end: input.selectionEnd,
pattern: RegExp('^' + input.dataset.filter + '$')
};
input.addEventListener('input', event => {
if (state.pattern.test(input.value)) {
state.value = input.value;
} else {
input.value = state.value;
input.setSelectionRange(state.start, state.end);
}
});
input.addEventListener('keydown', event => {
state.start = input.selectionStart;
state.end = input.selectionEnd;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment