Created
September 21, 2020 15:55
-
-
Save JamiesonRoberts/b7c3eddd45949e477b2ef6017e587a3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'core-js/es/array/from'; | |
const stringCleaner = str => { | |
const sanitized = Array | |
.from(str) | |
.filter(char => /[\u0020-\u007e\u00a0-\u00ff\n\r]/.test(char)) | |
.join('') | |
return {sanitized, hasBeenModified: (str.length > sanitized.length)} | |
} | |
function inputStateHandler(field) { | |
let timer; | |
function showError() { | |
const errorMessage = `<span id="error-${timer}" class="characterSetError">Entered characters not accepted and have been removed.</span>`; | |
field.insertAdjacentHTML('afterend',errorMessage) | |
} | |
function hideError() { | |
clearTimeout(timer); | |
const error = document.getElementById(`error-${timer}`); | |
if (error) { | |
error.remove(); | |
} | |
timer = undefined; | |
} | |
function changeEventHandler(e) { | |
const {sanitized, hasBeenModified} = stringCleaner(e.target.value); | |
e.target.value = sanitized; | |
if (!hasBeenModified) { | |
return; | |
} | |
if (typeof timer !== undefined) { | |
hideError(timer); | |
} | |
timer = setTimeout(hideError, 4000); | |
showError(e.target); | |
} | |
field.addEventListener('input', changeEventHandler) | |
field.addEventListener('change', changeEventHandler) | |
} | |
const fieldDetect = node => Array | |
.from(node.querySelectorAll('input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"]):not([type="submit"]):not([type="email"]):not([type="password"]),textarea')) | |
.forEach(inputStateHandler) | |
function initialize() { | |
fieldDetect(document.body); | |
const observer = new MutationObserver((mutationsList) => { | |
for (let mutation of mutationsList) { | |
if (mutation.type === 'childList') { | |
Array | |
.from(mutation.addedNodes) | |
.filter(ele => ele.tagName === "FORM" || ele.tagName === "INPUT" || ele.tagName === "TEXTAREA") | |
.forEach(fieldDetect); | |
} | |
} | |
}); | |
observer.observe(document.body, { | |
attributes: true, | |
childList: true, | |
subtree: true, | |
}); | |
} | |
const onReadyStateChange = () => { | |
if (document.readyState !== 'loading') { | |
return initialize(); | |
} | |
document.onreadystatechange = onReadyStateChange; | |
}; | |
onReadyStateChange(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment