The end result will be something like this:
For an easy explanation we’ll split the email-input component into 4 parts: template, inputs, logic and registration.
The first step is to create the template-element and set its innerHTML property to the HTML and the styling for our email-input component.
Following parts are defined:
- Label that will display the input-title ‘Email’
- Input field that will be validated when it loses focus
- Container for the validation text, hidden by default
- Styling for the validation text (class will be added in component logic)
By providing 2 input properties (validmessage and invalidmessage) we give the user of the component the ability to customize the validation message via attributes. We’ll use the property in the logic after the value of input-field is validated.
The logic is wrapped in the connectedCallback-function. This function is invoked each time the custom element is appended to the document-connected element.
The logic itself consists of different parts:
- Registration of the ShadowDOM, more info can be found here
- Getting a reference to the input-field and the element which will contain the validation text
- 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:
- Only validate when the input value is not empty, otherwise hide the validation text element
- Validation logic with a certain regex to validate the value of the input-field
- Use the validmessage/invalidmessage attribute inputs as the validation text, or provide a default message if the attributes are not used
- Add the corresponding class to the validation text element to use the styling declared in the template
- Make sure the validation text element becomes visible after the input was validated
Custom element registration
The last thing we need to do before we can use our email-input element in a web application is registering the HtmlElement class on the page using the define() method.
The full code example of the EmailInput-component can be found here.
Using a Custom Element
The big advantage of WebComponents is that after the component is registered as a CustomElement, it can be easily included and used in any webapplication (Vue.JS, Angular, React…).
The only thing that needs to be done is adding a script tag of type “module” with the src-attribute set to the location of the component. Typically this will point to a folder within the node_modules folder if the component was installed using NPM. If the script tag is in place, you can use the custom element like any other HTML-element!
Reach out to me for any questions about WebComponents in general.