Created
December 10, 2018 16:33
-
-
Save jenshelderweirdt/c9a4086e3819bf8a7b2884d90682b837 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
const template = document.createElement('template'); | |
template.innerHTML = ` | |
<label for="email-input">Email</label> | |
<input type="text" id="email-input" name="email-input"> | |
<div> | |
<small style="visibility: hidden;" id="validationtext"></small> | |
</div> | |
<style> | |
.invalid { | |
color: red; | |
} | |
.valid { | |
color: green; | |
} | |
</style> | |
`; | |
class EmailInput extends HTMLElement { | |
constructor() { | |
super(); | |
} | |
get validmessage() { | |
return this.getAttribute('validmessage'); | |
} | |
set validmessage(val) { | |
this.setAttribute('validmessage', val) | |
} | |
get invalidmessage() { | |
return this.getAttribute('invalidmessage'); | |
} | |
set invalidmessage(val) { | |
this.setAttribute('invalidmessage', val) | |
} | |
connectedCallback() { | |
this.attachShadow({ mode: 'open' }); | |
const instance = template.content.cloneNode(true); | |
this.shadowRoot.appendChild(instance); | |
const emailInput = this.shadowRoot.getElementById('email-input'); | |
const validationText = this.shadowRoot.getElementById('validationtext'); | |
emailInput.onblur = () => { | |
if (emailInput.value.length > 0) { | |
var regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
if (regex.test(String(emailInput.value).toLowerCase())) { | |
validationText.innerHTML = this.validmessage || "Default valid message!"; | |
validationText.classList.add("valid"); | |
} | |
else { | |
validationText.innerHTML = this.invalidmessage || "Default invalid message!"; | |
validationText.classList.add("invalid"); | |
} | |
validationText.style.visibility = "visible"; | |
} | |
else | |
validationText.style.visibility = "hidden"; | |
}; | |
} | |
} | |
window.customElements.define('email-input', EmailInput); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment