To recreate the maxlength and minlength validation with multiple messages, we need to separate them into multiple validators, and run them all one a time, breaking at the first invalid one. For attachment solution, it now looks like this
// validate.attach
// the validator now has to props: the "v" (function) and the "m" (message)
export function olvalidates(validators: { v: (value: any) => boolean; m?: string }[]): Attachment {
return (element: any) => {
// on input, go through all validators and break on first invalid
element.addEventListener(
'input',
(_) => {
// check one at a time
for (const v of validators) {
if (!_checkValidity(element, v)) break;
}
},
{ capture: true },
);
// validate custom event
element.addEventListener(
'olvalidate',
() => {
for (const v of validators) {
if (!_checkValidity(element, v)) break;
}
}
);
return () => {
// stop listning...
};
};
}
// read the extra message in validation function
const _checkValidity = (
node,
validator: { v: (value: any) => boolean; m?: string },
): boolean => {
if (validator) {
// validate and return result
const result = validator.v?.(node.value);
// use message for cusome validation
node.setCustomValidity(result ? '' : validator.m || node.dataset.errorMessage || 'invalid');
return result;
}
return true;
};
This can be used as follows:
<OlInput placeholder="Skippy" >
{#snippet input(ref)}
<input class="w100" {@attach olvalidates([
{v: (v) => textMax(v, {max: 6}), m: 'Too large'},
{v: (v) => textMin(v, {min: 3}), m: 'Too short'}])}
{...ref}
required={true} type="text" bind:value={formState.skippy} id="skippy" />
{/snippet}
</OlInput>Where the validation functions are now separate:
// form.ts
export const textMax = (v: any, params: { max: number}): boolean => {
const length = v?.length || 0;
if (!length) return true;
if (!params?.max) return true;
return length <= params.max;
};
export const textMin = (v: any, params: { min: number}): boolean => {
const length = v?.length || 0;
if (!length) return true;
if (!params?.min) return true;
return length >= params.min;
};So now, our element validates all three edges correctly: required, minlength and maxlenght. Though personally, I would not use it for that, because the edge case can be handled with a generic message, the edge case is rare. Usually, the native HTML validation will kick in after user interaction. Nevertheless, having multiple validators goes a long way. So let's see how that looks in a wrapper function:
// OlInput.svelte
// add ne input prop
validators?: { v: (value: string) => boolean; m?: string }[]
// change the attachment validators
node.addEventListener('input', (e) => {
if (validators) {
for (const v of validators) {
if (!_checkValidity(e.target, v)) break;
}
}
errorText = ErrorMessage(<HTMLInputElement>e.target);
});
// catch custom event as well
node.addEventListener('olvalidate', (e) => {
if (validators) {
for (const v of validators) {
if (!_checkValidity(e.target, v)) break;
}
}
});
// change check validity function, looks exactly like the attachment function, we can move it to form.ts
const _checkValidity = (node, validator: { v: (value: string) => boolean; m?: string }) => {
// check validation data attribute
if (validator) {
const result = validator.v?.(node.value);
node.setCustomValidity(result ? '' : validator.m || node.dataset.errorMessage || 'invalid');
return result;
}
return true;
};To use that in HTML
<OlInput placeholder="Skippy with validators" validators={[
{v: (v) => textMax(v, {max: 6}), m: 'Too large'},
{v: (v) => textMin(v, {min: 3}), m: 'Too short'}
]}
>
{#snippet input(ref)}
<input class="w100" {...ref} required={true} type="text" bind:value={formState.skippy} id="skippy" />
{/snippet}
</OlInput>anchorRemove event listeners
Before we go on, let's treat the "removal" of listeners. Svelte reruns the attachments on every change it detects, so we need to clean up regularly. One way is the usual way, save the function in its own variable, pass it on listen, and on remove listeners.
element.removeEventListener(..., handler);A more modern way is to use a signal
// validate.attach
export function olvalidates(...): Attachment {
return (element: HTMLInputElement) => {
// define the abort controller
const controller = new AbortController();
element.addEventListener(
'input', handler,
// pass abort controller signal
{ capture: true, signal: controller.signal },
);
// ...
return () => {
// aborte
controller.abort();
};
};
}In wrapper function, it is the same, the controller is defined in context of the attachment itself, then aborted on attachment return body.
I still have not made up my mind, wrapper functions or input attachments. Let's move on to other types.
anchorValidate select options
The required input validation means the select drop down needs to have a selected value.
<OlInput placeholder="Operating system" >
{#snippet input(ref)}
<select class="w100" required={true} bind:value={formState.os} id="os" {...ref} >
<option value={1}>Windows</option>
<option value={2}>Mac</option>
<option value={3}>Linux</option>
</select>
{/snippet}
</OlInput>Adding required is all it takes to validate for at least one. For number values, make sure the value is inside curly brackets. Setting the value on initialization does not need any further adjustments, It just works out of the box.
anchorValidating a checkbox
The checkbox can also be passed as a reference, and it will validate if "checkbox" is required, example: terms and conditions.
<OlInput placeholder="Terms and conditions">
{#snippet input(ref)}
<input type="checkbox" {...ref} name="accept" required={true} id="terms" bind:checked={formState.terms} />
{/snippet}
</OlInput>The label appears before the checkbox, so to fix this, we need to adjust our css. We can be smart, and pass the css into the wrapper, or be smartasses, and write a css selector that targets a checkbox. Let Steve do the smartass-ing. We'll just pass the css into the wrapper.
<script>
// define extra prop in OnInput.sveltte: css
interface IProps {
// ...
css?: string;
}
const { css ...}: IProps = $props();
// then simply add it to the root element,
// then let your component style decide the style
</script>
<div class="ol-field {css}" ... >
</div>
<style>
/* example only */
.ol-field.ol-checkbox {
.ol-input {
}
.ol-label {
/* make it look different */
}
}
</style>The idea of passing the css instead of wrapping the outside component, is to let our component robust enough so that we don't have to define new classes per type. And that only works if the styles are "native to the component". The required validation works as expected but the error message probably should be more deliberate. We can use custom validation for it:
<OlInput placeholder="Terms and conditions" css="ol-checkbox" validators={[
{
// this actually does not work properly
v: (value) => !!formState.terms,
m: 'You have to accept'
}
]}>
{#snippet input(ref)}
<input type="checkbox" {...ref} name="accept" id="terms" bind:checked={formState.terms} />
{/snippet}
</OlInput>Having custom messages is so rare in my decades of experience, I am not going to try to control it beyond this.
But the issue that needs attention is that formState.terms is updated after the input event fires. So checking and unchecking the checkbox, will not report the right checked value. Two possible solutions:
anchorPass node back to validator
I've already tried this before and I did not like it, it involves changing the signature of the validator function to allow the node to be sent back.
// validators, add the node definition
validators?: { v: (value: string, node?: any) => boolean; m?: string }[];
const _checkValidity = (node, validator) => {
if (validator) {
// then pass the node back to validator
const result = validator.v?.(node.value, node);
node.setCustomValidity(result ? '' : validator.m || node.dataset.errorMessage || 'invalid');
return result;
}
return true;
};
// then later in the component:
// change this v: (value) => !!formState.terms,
// to:
v: (value, node) => !!node.checked,anchorPass checked instead of value
In our custom validation functions, we can conditionally pass the node checked status. This is a much cleaner solution, but a bit rigid.
const _checkValidity = (node, validator: { v: (value: any) => boolean; m?: string }) => {
if (validator) {
// pass checked instead of value
const result = validator.v?.(node.type === 'checkbox' ? node.checked : node.value);
node.setCustomValidity(result ? '' : validator.m || node.dataset.errorMessage || 'invalid');
return result;
}
return true;
};I went with this easier solution.
anchorValidating radio buttons
A radio button group is also straight forward, just needs css touch up. It is better to have one radio button selected by default, but sometimes, you are dealing with a stubborn dinosaur who thinks users should select one of the options so they are "responsible" for their choices. They have not yet joined the TikTok era! At this point, a required flag should be enough:
<OlInput placeholder="I accept" css="ol-radios">
{#snippet input(ref)}
<input type="radio" {...ref} id="yes" required={true} bind:group={formState.accept} name="accept" value="yes" />
<label for="yes"> Yes </label>
<input type="radio" {...ref} id="no" required={true} bind:group={formState.accept} name="accept" value="no" />
<label for="no"> No </label>
{/snippet}
</OlInput>This flags all inputs as "invalid". To make use of {...ref} we need to pass the id, because the component has the same id for all refs. The trick now is to recreate the style so that it responds to the invalid of input fields, then look for any invalid radio input, I want to end up with a group of radio buttons contained in an ol-field. Let's start with a new prop: type.
If type is "group", I want to move the ol-input higher up the field stack.
<script>
interface IProps {
// one more prop
type?: 'group' | 'field';
}
const { type = 'field', ... }: IProps = $props();
</script>
<!-- Add class to wrapper conditionally -->
<div class:ol-input={type === 'group'} {id}>
...
</div>This could be enhanced by making a new internal wrapper, and adding a new class. You would want to do that if you have a more complicated layout. For our project, this suffices.
anchorHidden inputs
It is rare to validate hidden inputs, but they can be quite handy, to validate complex scenarios. Hidden inputs are not part of the native validation process, no input, no invalid event, and no set custom validation is possible. So the solution is to use a text input, hidden!
<OlInput placeholder="Colors" validators={
[
{v: (value) => !!value, m: 'At least one'}
]}
css="ol-checkboxes" type="group">
{#snippet input(ref)}
<div >
<label>
<input type="checkbox" id="red" value="red" bind:group={formState.colors} />
Red
</label> <br />
<label>
<input type="checkbox" id="black" value="black" bind:group={formState.colors} />
Black
</label> <br />
<label>
<input type="checkbox" id="green" value="green" bind:group={formState.colors} />
Green
</label> <br />
</div>
<!-- this input is text, and it's part of validation, it's just hidden -->
<input type="text" hidden {...ref} id="colors" value={formState.colors?.length ? 1 : null}>
{/snippet}
</OlInput>This does not update on changes because there is no input events to catch. If we use required we get a better responsive behavior but the message is still "Required."
We can also use data-pattern that is responsive, and the message of the invalid pattern can be looked up instead of hard coded in form. As a matter of fact, one last fix can make some of these problems go away:
anchorCustom error messages
That last bit is to create a map of all messages, with fallback, and allow a suffix to modify it
// form.ts
export const ErrorMessage = (input: HTMLInputElement) => {
const _suffix = input.dataset?.suffix || '';
if (validity.valueMissing) {
return customMessages.get('Required' + suffix);
}
// ...
}
// definet the map with fallbacl
export const customMessages = new Map<string, any>([
['Required', 'Required'], // fallback
['Required_atleastone', 'At least one'],
]);Now if we want to show "at least one" instead of "required", we assign a data-suffix to the input:
<input type="text" required={true} data-suffix='_atleastone' {...ref} >Now let's cover the last challenging bit:
anchorCheckbox group
This is probably historically the most challenging one. For some reason, HTML does not identify the group of checkboxes to have any significant meaning. The one validation we are looking for is: select at least one. There are three ways we can do this, they all involve a "hidden" text input, the first one mentioned above, custom validation. The second one is pattern lookup:
<input type="text" data-pattern={'oneitem'} hidden {...ref} id="colors" value={formState.colors?.length ? 1 : 0}>
The pattern then is added to form input patterns:
// form.ts
export const InputPatterns = new Map<string, any>([
['oneitem', '[123456789]{1,}'],
]);Or it can be simple: required. But with data suffix, we can adjust the message
<input type="text" required={true} hidden data-suffix='_atleastone' {...ref} id="colors" value={formState.colors?.length ? 1 : null}>This is responsive. This is a conclusion. Enough.
anchorConclusion
This as a good exercise, not to create a custom control for Svelte, but rather to learn all the native HTML validation techniques. It is astounding how little Svelte can do out of the box though, compared to the same exercise I had previously to create the same outcome in Angular.
Final note: I could not make up my mind yet, input attachments, or wrapper functions? I have not been able to reach a conclusion as to which works better than the other.
Happy belated Tuesday. đŸ˜´