Skip to content

Instantly share code, notes, and snippets.

@jenshelderweirdt
Last active December 12, 2018 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jenshelderweirdt/1c80d70aa56d0817ccc1fe68ca472080 to your computer and use it in GitHub Desktop.
Save jenshelderweirdt/1c80d70aa56d0817ccc1fe68ca472080 to your computer and use it in GitHub Desktop.
connectedCallback() {
//Registration of the ShadowDOM
this.attachShadow({ mode: 'open' });
const instance = template.content.cloneNode(true);
this.shadowRoot.appendChild(instance);
//Getting a reference to the input-field and the element which will contain the validation text
const emailInput = this.shadowRoot.getElementById('email-input');
const validationText = this.shadowRoot.getElementById('validationtext');
//An eventlistener for the onBlur event of the input-field.
//This will fire the moment that the element loses focus.
//The rest of the logic will be wrapped into this function as we want to run the logic each time the element loses focus.
emailInput.onblur = () => {
//Only validate when the input value is not empty, otherwise hide the validation text element
if (emailInput.value.length > 0) {
//Validation logic with a certain regex to validate the value of the input-field
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())) {
//Use the validmessage attribute inputs as the validation text, or provide a default message if the attributes are not used
validationText.innerHTML = this.validmessage || "Default valid message!";
//Add the corresponding class to the validation text element to use the styling declared in the template
validationText.classList.add("valid");
}
else {
//Use the invalidmessage attribute inputs as the validation text, or provide a default message if the attributes are not used
validationText.innerHTML = this.invalidmessage || "Default invalid message!";
//Add the corresponding class to the validation text element to use the styling declared in the template
validationText.classList.add("invalid");
}
//Make sure the validation text element becomes visible after the input was validated
validationText.style.visibility = "visible";
}
else
validationText.style.visibility = "hidden";
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment