DileNativeValidity
This mixin makes form-associated fields take part in the constraint validation of native HTML forms. It is applied to the Dile form fields (dile-input and all its variants, dile-textarea, dile-select, dile-checkbox, dile-radio-group, dile-select-boolean, dile-select-overlay, dile-select-ajax, dile-select-search, dile-number-picker, dile-otp-input, dile-input-suggestions, dile-drop-file, dile-editor, dile-datepicker, dile-time-picker, dile-rating-scale-question, dile-wheel-picker, dile-order-switch, dile-country-select, dile-select-ajax-simple...), so you only need it for your own fields.
Inside a plain <form>, without DileForm:
- A field with
requiredand no value is invalid (valueMissing), and the form is not sent. - A field whose
getValidationError()returns a message is invalid (customError), like an impossible date indile-datepicker, an incompletedile-input-maskor a text that is not a number indile-input-money. form.checkValidity(),form.reportValidity(), theinvalidevent, the:invalidpseudo-class and thenovalidateattribute work as with native inputs.
<form>
<dile-input name="email" label="Email" required></dile-input>
<dile-checkbox name="terms" required>I accept the terms</dile-checkbox>
<dile-button type="submit">Send</dile-button>
</form>
The rules of @dile/validation (email, minLength...) are not checked here: they need a DileForm with the DileFormValidation mixin. In a DileForm, use its validate() method, which also shows the errors in the fields.
Usage
The field must be form-associated and keep its ElementInternals in the internals property:
import { LitElement, html } from 'lit';
import { DileNativeValidity } from '@dile/ui/mixins/form';
class MyField extends DileNativeValidity(LitElement) {
static formAssociated = true;
static properties = {
value: { type: String },
required: { type: Boolean, reflect: true },
};
constructor() {
super();
this.internals = this.attachInternals();
}
updated(changedProperties) {
if (changedProperties.has('value')) {
this.internals.setFormValue(this.value ?? '');
}
}
get el() {
return this.shadowRoot.querySelector('input');
}
render() {
return html`<input .value=${this.value ?? ''} @input=${e => this.value = e.target.value}>`;
}
}
The validity is updated after every render of the field. It uses:
- required: marks the field as required.
- isEmpty() (optional): returns
truewhen the field has no value. Without it,undefined,null, empty or whitespace-only strings and empty arrays are empty, the same criterion as DileForm. - getValidationError() (optional): returns the error message of the field, or
''. It may return a promise. - disabled, isDisabled or readonly: these fields are not validated. Fields inside a disabled
<fieldset>are not validated either. - el (optional): the inner control, used by the browser to point to the error. Without it, the first focusable element of the shadow root is used.
Styling invalid fields
Browsers do not apply the :user-invalid pseudo-class to custom elements. Instead, an invalid field gets the user-invalid attribute, and the user-invalid custom state, after the user leaves it or tries to submit its form. A form reset removes it. :invalid matches from the start, like with native inputs.
dile-input[user-invalid],
dile-checkbox:state(user-invalid) {
outline: 2px dashed #c00;
outline-offset: 4px;
}
Inside a DileForm, use the errored state of the fields instead: the form shows the errors when it validates.
In a native form, fields inside closed containers (like a dile-slide-menu) are not revealed when the form is submitted: the invalid event is also dispatched by checkValidity(), which only queries the state, and the browser tries to focus the field synchronously, before a container could open. Inside a DileForm, validate() reveals and focuses them with the dile-reveal event.
Properties
- validity: the
ValidityStateof the field. - validationMessage: the message of the current error, or
''. - willValidate:
truewhen the field takes part in the validation of its form. - validityAnchor: the element the browser points to when it shows the error.
- userInvalid:
truewhen the field is invalid after the user left it or tried to submit the form. Reflected in theuser-invalidattribute.
Methods
- checkValidity(): returns
truewhen the field is valid. Otherwise it dispatches aninvalidevent and returnsfalse. - reportValidity(): like
checkValidity(), and the browser shows the error message. - setCustomValidity(message): sets a custom error, as in native controls. An empty string removes it.
- formResetCallback(): called by the browser when the form is reset. It clears the
user-invalidstate: fields that override it to restore their value must callsuper.formResetCallback(). - updateValidity(): recomputes the validity. Call it when something that is not a reactive property changes the result of
getValidationError().
The message of valueMissing is "This field is required." in English or Spanish, depending on the language of the field: the closest lang attribute or DileForm with a language, the default language (setDefaultLanguage()) or the document language. See Language of the messages.
DileNativeValidity demos
Native form
<script type="module">
import '@dile/ui/components/input/input.js';
import '@dile/ui/components/checkbox/checkbox.js';
import '@dile/ui/components/button/button.js';
</script>
<form id="nativeValidityForm">
<dile-input name="email" label="Email" required></dile-input>
<dile-checkbox name="terms" required>I accept the terms</dile-checkbox>
<p><dile-button type="submit">Send</dile-button></p>
<p id="nativeValidityResult"></p>
</form>
<script>
const form = document.getElementById('nativeValidityForm');
form.addEventListener('submit', (e) => {
e.preventDefault();
document.getElementById('nativeValidityResult').textContent = 'Sent: ' + JSON.stringify(Object.fromEntries(new FormData(form)));
});
</script>
dile-components