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:
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 validators only
With validators and event options
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
A validationMessageOptions must be Type
resetOn?: keyof HTMLElementEventMap,
setOn?: keyof HTMLElementEventMap,
}
With validationMessageSetter only
With validationMessageSetter and options
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
With validationMessageSetter and options
resetOn?: “change“, // default
setOn?: “invalid“, // default
}]}>
With validationMessageSetter, validators and options
resetOn?: “change“, // default
setOn?: “invalid“, // default
reportOn?: “change“, // default
}]}>