RichInput
A colourful <input> element
RichInput is a Web Component that extends the native text input to provide real-time colorization of user input.
RichInput behaves like a standard text <input> and
can be used as a direct replacement for elements with a type of text
,
email
, tel
, or url
.
User input is colourized using a regular expression pattern, which is
provided via the stylepattern
HTML attribute. The capture
groups of the expression are used to style the output. Here's the markup
for the example above:
<kc-richinput stylepattern="([^@]+)@?(.*)?"></kc-richinput>
In this case, the pattern ([^@]+)@?(.*)?
is used to split
the input text into two capture groups: the first group ([^@]+)
matches one or more characters before an optional "@" symbol, and the second
group (.*)?
captures any characters following it.
Note: The regular expression pattern must match the entire user input. Internally, the pattern is prefixed with "^(?:", and suffixed with ")$". This matches the native behavior of the <input> pattern property.
The component exposes each of these capture groups as stylable regions
that can be accessed using the CSS ::part
pseudo-element.
Using a few lines of CSS it's possible to contextually highlight the user
and domain parts of an email-like string:
/** Capture group 1 */
::part(group-1) {
color: #5078f0;
}
/** Capture group 2 */
::part(group-2) {
color: #14f014;
}
Under the hood, the RichInput component leverages a
native <input>
element as its core input mechanism. This
ensures users benefit from browser-native behaviors and accessibility
features. Since this is based on a standard input element, only a small
subset of CSS properties can be used to style capture groups:
color
background-color
text-decoration
text-shadow
Examples
<kc-richinput
id="email-example"
type="email"
value="email@mysite.com"
stylepattern="([^@]+)@?(.*)?"
></kc-richinput>
#email-example::part(group-1) {
color: #df2020;
}
#email-example::part(group-2) {
color: #df9f20;
}
<kc-richinput
id="url-example"
type="url"
value="https://site.com/index.html?id=1"
stylepattern="(\w+)(?::/?/?)?(?:([^/]+)?(?:/?)([^?]*)(?:\??))(.*)"
></kc-richinput>
#url-example::part(group-1) {
color: #e61919;
}
#url-example::part(group-2) {
color: #c08819;
}
#url-example::part(group-3) {
color: #30a730;
}
#url-example::part(group-4) {
color: #188dd1;
}
<kc-richinput
id="tel-example"
type="tel"
value="01234567890"
stylepattern="(0\d{0,4})\s*(\d*)"
></kc-richinput>
#tel-example::part(group-1) {
color: #df2020;
text-shadow: 3px 3px #d224;
}
#tel-example::part(group-2) {
color: #df9f20;
text-shadow: 3px 3px #d904;
}
How to use
Using RichInput in a build tool / bundler:
If you're building on top of a framework or use build tooling such as Vite or Rollup, you can install the module as a dependency:
npm install git+https://github.com/keithclark/richinput
You can now import the element from the module and define it in the
component registry using your preferred tag name. In this example we're
using kc-richinput
:
import RichInputElement from '@keithclark/richinput';
customElements.define('kc-richinput', RichInputElement);
Using RichInput directly in a browser:
Method 1: Use a local copy of the module:
Download the minified JavaScript module into your project, import the element and register it:
<script type="module">
import RichInputElement from './path/to/element.js';
customElements.define('kc-richinput', RichInputElement);
</script>
Method 2: Load from a CDN:
Import the component directly from a CDN and register it:
<script type="module">
import RichInputElement from 'https://cdn.jsdelivr.net/gh/keithclark/richinput@1.0.1/dist/richinput.js';
customElements.define('kc-richinput', RichInputElement);
</script>
Documentation
The richinput HTML element
RichInput enhances the native text-based <input> form element, providing real-time colourization of user input using a Regular Expression pattern. A richinput element can be manipulated with JavaScript using the RichInputElement interface.
HTML Attributes
-
autocomplete
-
Indicates whether the input value can be automatically completed by the browser. For information on allowed values please see: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill. Can be one of
"<token-list>"
,"off"
or"on"
. -
disabled
-
A boolean attribute. Controls whether the user is able interact with the input, or not. A disabled input cannot receive focus or have it's value modifed by the user.
-
maxlength
-
Determines the maximum number of characters permissable in the value.
-
pattern
-
A string containing a regular expression that the user's input must match. The regular expression must match the entire input value, rather than matching a substring.
-
placeholder
-
A text string that is displayed in the field as a prompt until the user puts focus on the field.
-
readonly
-
A boolean attribute. Determines whether a user can modify the input value. An input marked as read-only can receive focus.
-
required
-
A boolean attribute. Determines if the user must supply a value for this input for it to be considered valid. If the input is marked as required and a value is missing, the user will be prompted to set one when attempting to submit a form.
-
stylepattern
-
The regular expression pattern used to control styling of the input value. It's compiled with the
v
flag, so it's Unicode-aware. The pattern must match the entire input value—not just part of it. -
type
-
Controls the type of value the input should contain. If omitted or set to invalid value, the default value of
text
will be implied. Can be one of"email"
,"tel"
,"text"
or"url"
. -
value
-
The text content of the input.
RichInputElement Class
The RichInputElement interface represents richinput
elements in the DOM. richinput is a Web Component and extends the HTMLElement interface. This means it also has access to all the methods and properties from HTMLElement, as well as those from its parent interfaces: Element, Node, and EventTarget.
Instance Methods
-
checkValidity()
-
Indicates if the input has any validation issues.
Syntax
result = instance.checkValidity()
Returns
A boolean.
-
focus()
-
Programatically set the focus to the input.
Syntax
instance.focus(options)
Arguments
-
options
- A Object.
-
-
reportValidity()
-
Performs a validation check and reports any resulting failure to the user. If this input has an associated form element, the form submission will be prevented until the element is in a valid state.
Syntax
result = instance.reportValidity()
Returns
A boolean.
-
select()
-
Sets the current selection to the text content of the input.
Syntax
instance.select()
-
setCustomValidity()
-
Sets a custom validity message for the input. When a validation check is performed by
reportValidity
, this message will be shown to the user. To stop showing the message call this method with an empty string.Syntax
instance.setCustomValidity(message)
Arguments
-
message
- A string.
-
-
setRangeText()
-
Sets the start and end positions of the text selection in the element.
Syntax
instance.setRangeText(replacement, start, end, selectMode)
Arguments
-
replacement
- A string. The string to insert.
-
start
optional -
A number. The index of the first character to replace. Defaults to the current
selectionStart
value. -
end
optional -
A number. The index of the character after the last character to replace. Defaults to the current
selectionEnd
value. -
selectMode
optional -
A string. Selection state after the text has been replaced. Allowed values:
'end'
,'preserve'
,'select'
or'start'
Note: As per the HTML5 spec, this method will throw a
InvalidStateError
exception for inputs with a type ofemail
. -
-
setSelectionRange()
-
Sets the start and end positions of the text selection in the element.
Syntax
instance.setSelectionRange(selectionStart, selectionEnd, selectionDirection)
Arguments
-
selectionStart
- A number. The index of the first selected character.
-
selectionEnd
- A number. The index of the last selected character.
-
selectionDirection
optional -
A string. Direction the selection was made. Allowed values:
'backward'
,'forward'
or'none'
Note: As per the HTML5 spec, this method will throw a
InvalidStateError
exception for inputs with a type ofemail
. -
Instance Properties
-
autocomplete
-
A string. Indicates whether the input value can be automatically completed by the browser. For information on allowed values please see: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill. One of:
"<token-list>"
,"off"
or"on"
. Reflects the element'sautocomplete
attribute. -
disabled
-
A boolean. Controls whether the user is able interact with the input, or not. A disabled input cannot receive focus or have it's value modifed by the user. Reflects the element's
disabled
attribute. -
form
Read Only -
A HTMLFormElement. Returns the form assosicated with the element, or
null
if a form is not available. -
list
Read Only -
A HTMLDataListElement or null. Returns a reference to the
<datalist>
element referred to by thelist
attribute, ornull
if the attribute is not present or the list it refers to is not accessible.Note: A clone of the
<datalist>
element reference by this property will be appended to the Shadow DOM when the input receives focus. This is required because the element that captures user input is located in the Shadow DOM and cannot access elements in the Light DOM. The clone is destroyed once the element loses focus. -
maxLength
-
A number. Determines the maximum number of characters permissable in the value. Reflects the element's
maxlength
attribute. -
pattern
-
A string. A string containing a regular expression that the user's input must match. The regular expression must match the entire input value, rather than matching a substring. Reflects the element's
pattern
attribute. -
placeholder
-
A string. A text string that is displayed in the field as a prompt until the user puts focus on the field. Reflects the element's
placeholder
attribute. -
readOnly
-
A boolean. Determines whether a user can modify the input value. An input marked as read-only can receive focus. Reflects the element's
readonly
attribute. -
required
-
A boolean. Determines if the user must supply a value for this input for it to be considered valid. If the input is marked as required and a value is missing, the user will be prompted to set one when attempting to submit a form. Reflects the element's
required
attribute. -
selectionDirection
-
A null or string. Gets or sets direction the current text selection was made.
Note: As per the HTML5 spec, this property will return
null
for inputs with a type ofemail
. One of:"backward"
,"forward"
or"none"
. -
selectionEnd
-
A null or number. Gets or sets the index of the last character in the text selection or the caret position, if nothing is selected.
Note: As per the HTML5 spec, this property will return
null
for inputs with a type ofemail
. -
selectionStart
-
A null or number. Gets or sets the index of the first character in the text selection or the caret position, if nothing is selected.
Note: As per the HTML5 spec, this property will return
null
for inputs with a type ofemail
. -
stylePattern
-
A string. The regular expression pattern used to control styling of the input value. It's compiled with the
v
flag, so it's Unicode-aware. The pattern must match the entire input value—not just part of it. Reflects the element'sstylepattern
attribute. -
type
-
A string. Controls the type of value the input should contain. If omitted or set to invalid value, the default value of
text
will be implied. One of:"email"
,"tel"
,"text"
or"url"
. Reflects the element'stype
attribute. -
validationMessage
Read Only -
A string. The current validation error message to show the user.
-
validity
Read Only -
A ValidityState. Returns the current validity state of the input.
-
value
-
A string. The text content of the input. Reflects the element's
value
attribute. -
willValidate
Read Only -
A boolean. Indicates whether this input will participate in validation or not.