Skip to content

Instantly share code, notes, and snippets.

@alonbardavid
Created September 2, 2019 11:45
Show Gist options
  • Save alonbardavid/dbaf81258f92dd61a17504d6f3b09af1 to your computer and use it in GitHub Desktop.
Save alonbardavid/dbaf81258f92dd61a17504d6f3b09af1 to your computer and use it in GitHub Desktop.
function myComponent(selector,label,value,onChange,validations = {},format=null){
let element = document.querySelector(selector);
element.innerHTML=```
<div class="my-element">
<label>${label}</label>
<input></input>
</div>
```
let input = element.querySelector('input');
input.value = value;
input.addEventListener('input', e=>{
let raw = e.target.value;
if (validations.maxLength && raw.length > validations.maxLength
|| validations.pattern && validations.pattern.test(raw)){
// for simplicity we are going to assume input events are cancelable
e.preventDefault();
} else {
if (format) {
raw = format(raw);
input.value = raw;
}
onChange(raw);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment