TL;DR: the code
SolidJS use:validation
directive
Validator function
Both customValidity
and validation
directives must / can be used with custom validator(s).
A validator
is a sync or async function that takes an HTMLElement that implements the Constraint Validation API and returns an (i18n) error validation message or an empty string when valid.
Refered here as HTMLElement_Validation
, the element can be either a HTMLButtonElement
, HTMLFieldSetElement
, HTMLInputElement
, HTMLOutputElement
, HTMLSelectElement
, or HTMLTextAreaElement
.
/**
* validator function
* @param {HTMLElement_Validation} element The element to validate
* @returns {string|Promise<string>} Empty string `""` when the element is valid, the i18n custom error `validationMessage` otherwise.
*/
type validator = (element: HTMLElement_Validation) => string | Promise<string>;
Example of a sync validator
that constraint an input
element to have a value with a non empty string:
function hasNonEmptyValue(element: HTMLElement_Validation): string {
const value = (element as HTMLInputElement).value.trim();
const errored = value === "";
return errored ? "Text must not be empty" : "";
}
Usage of the customValidity
directive
The reportValidity
function is called upon the reportOn
event type i.e change
(default), blur
, input
.
In the example below, we use the directive on an input
HTMLInputElement.
- With
validator
s only
<input use:customValidity={[validator, validator]}>
- With
validator
s and event options
<input use:customValidity={[validator, validator, {
reportOn: "change" // default
}]}>
Usage of the validationMessage
directive
This directive is useful to synchronize an element validationMessage
with a Signal<string>
.
A validationMessageSetter
must be Type
Setter<string>
A validationMessageOptions
must be Type
{
resetOn?: keyof HTMLElementEventMap,
setOn?: keyof HTMLElementEventMap,
}
- With
validationMessageSetter
only
<input use:validationMessage={validationMessageSetter}>
- With
validationMessageSetter
and options
<input use:validationMessage={[validationMessageSetter, {
resetOn?: "change", // default
setOn?: "invalid" // default
}]}>
Usage of the validation
directive
This directive is the combination of the customValidty
and validationMessage
directive.
A validationOptions
must be Type
{
resetOn?: keyof HTMLElementEventMap,
setOn?: keyof HTMLElementEventMap,
reportOn?: keyof HTMLElementEventMap,
}
- With
validationMessageSetter
only
<input use:validation={validationMessageSetter}>
- With
validationMessageSetter
and options
<input use:validation={[validationMessageSetter, {
resetOn?: "change", // default
setOn?: "invalid", // default
}]}>
- With
validationMessageSetter
,validator
s and options
<input use:validation={[validationMessageSetter, [validator, validator], {
resetOn?: "change", // default
setOn?: "invalid", // default
reportOn?: "change", // default
}]}>
Top comments (0)