Skip to content

Instantly share code, notes, and snippets.

@kdssoftware
Created August 27, 2021 10:27
Show Gist options
  • Save kdssoftware/343710f6110fa7cc861e78fae53cd6c5 to your computer and use it in GitHub Desktop.
Save kdssoftware/343710f6110fa7cc861e78fae53cd6c5 to your computer and use it in GitHub Desktop.
/**
* component last updated by Karel De Smet 27/08/2021
* ------------------------ (github.com/snakehead007)
*
* How to use:
* --
* add to an input element 1 or more checkers to its class and add a data- accordingly
* e.g. `<input id="some-text" class="form_checker-is_empty" data-is_empty="this message will be shown when its empty"/>`
*
* the error message will be shown where the id prefix is the same as the input id.
* e.g. `<small id="form_checker-some-text" class="form_checker"> </small>`
*
*
* all types:
* - is_empty //checks if the input isnt empty
* - is_short //checks if the input is shorten than a given number e.g. 'is_short' 'is_short_length'
* - is_email //checks if the input is an email address
*/
/**
* How to build your own types?
* --
* add your type name to the `types` veriable
* add your type code to the switch case
*
*/
document.addEventListener('DOMContentLoaded', function () {
let suffix = "form_checker";
let errorClass = `${suffix}-error`;
let types=["is_empty","is_email","is_short"];
for (const type of types) {
console.log((`input.${suffix}-${type}`));
for (const el of document.querySelectorAll(`input.${suffix}-${type}`)) {
console.log(`checking ${el.id}`);
for (const [type, valueOfType] of Object.entries(el.dataset)) {
switch (type){
//HERE ARE ALL THE TYPES DEFINED
case types[0]: //is_empty
console.log(`adding type ${type} to ${el.id}`);
el.addEventListener("keyup",function(){
addErrorMsgToEvents(el,type,(el.value?.trim()===""));
})
el.addEventListener("blur",function(){
addErrorMsgToEvents(el,type,(el.value?.trim()===""));
})
break;
case types[1]: //is_email
console.log(`adding type ${type} to ${el.id}`);
break;
case types[2]: //is_short
if(!el.dataset[types[2]+"_number"]){
console.log(types[2]+"_number is not defined in ",el);
}
console.log(`adding type ${type} to ${el.id}`);
el.addEventListener("blur",function(){
addErrorMsgToEvents(el,type,(el.value?.length<Number(el.dataset[types[2]+"_number"])));
el.addEventListener("keyup",function(){
addErrorMsgToEvents(el,type,(el.value?.length<Number(el.dataset[types[2]+"_number"])));
})
})
break;
}
}
}
}
function addErrorMsgToEvents(element,type,isError){
console.log(`Triggered! ${suffix}-${element.id}`,type,isError);
if(isError){
document.getElementById(`${suffix}-${element.id}`).innerText = element.dataset[type];
element.classList.add(errorClass);
}else{
document.getElementById(`${suffix}-${element.id}`).innerText = "";
element.classList.remove(errorClass);
}
}
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment