Sekrab Garage

Svelte Input Component

Custom validation and a bit of a fig leaf

Svelte November 24, 26
Subscribe to Sekrab Parts newsletter.
Series:

Form Validation in Svelte

This series is dedicated to Svelte Input component, which I will attempt to automate the validation without being obtrusive to the native HTML input elements, using native JavaScript validation.
  1. 28 days ago
    Programmatic attachment in Svelte
  2. 12 days ago
    Native Validation
  3. two days ago
    Custom validation and a bit of a fig leaf

anchorCharacter length validation

Last episode we stopped short of validating maxlength and minlength, because for some historical reason, browsers are stuck in history, and cannot validate the length, without real user input. Today we will create our fig leaf to cover this defect. We add a textarea and set its value programmatically to be more than the maxlength. Then submit form, to reproduce the issue.

The current state of this component can be found on Stackblitz
<script>
	const formState = $state({
	   history: 'here is the life span of a little junior grown too fast named Steve'
	});


const submit = (e) => {
	e.preventDefault
	if (!ValidateForm(e.target as HTMLFormElement)) {
		// is maxlength being caught on first validation? no
		return;
	}
	// go on
};
</script>
<OlInput placeholder="History">
	{#snippet input(ref)}
	  <input {...ref} type="text" bind:value={formState.history} id="history"
     maxlength="10" />
  {/snippet}
</OlInput>

anchor1. Using pattern instead of minlength

This choice is like telling a developer to write HTML without "div". But if you are a small team (yourself and Steve only), you might be able to commit to never using maxlengh and instead use a pattern match of length.

<OlInput placeholder="History">
  {#snippet input(ref)}
    <input {...ref} type="text" bind:value={formState.history} id="history"
    pattern={'.{0,30}'} data-format="history" />
  {/snippet}
</OlInput>

This will yield into "Invalid history format." Not perfect, even if we move it to data-pattern we still end up with this message. Let's see other solutions.

anchor2. Changing minlength and maxlength to pattern

We can programmatically change those to patterns to RegEx pattern as well:

// OlInput.ts

const refElement = {
    get pattern(){
		// overide native patter
      if (el) {
        // if element has pattern, keep it
        if (el.getAttribute('pattern')) {
          return el.getAttribute('pattern');
        }

        // if minlength, add a RegEx for it
        const minlength = el.getAttribute('minlength') || 0;
        const maxlength = el.getAttribute('maxlength') || '';
        el.setAttribute('data-format', 'length');

        if (minlength || maxlength) {
          return `.{${minlength},${maxlength}}`;
        }
      }
      return null;
    },
    // ...
  };

This too will produce an error Invalid length format only on first time validation, before user input. Not perfect. But it has an extra advantage over the first solution, and that is, on user input, maxlength validation kicks in, and the validation message is Too long. As it should be.

anchor3. Belated validation

Our last resort is belated special validation. Validating upon submission. We will set the custom validity to something, that will trigger the new attribute in input validity customError: true

// form.ts
// adapt the Validate function to catch minLength anyway
  
export const ValidateForm = (form: HTMLFormElement, toast: boolean = true): boolean => {
		const _minLengh = form.querySelectorAll('[minlength]') || [];
	  
    _minLengh.forEach((input: HTMLInputElement) => {
      input.setCustomValidity('');
      const value = input.value?.length || 0;
      const minLength = +(input.getAttribute('minlength') || 0);
      if (value < minLength) {
        input.setCustomValidity('Too short');
      }
  });

This will trigger the customError to be false. So now we just need a way to pass our special message, which can be found in element validationMessage

// form.ts
export const ErrorMessage = (input: HTMLInputElement) => {
	 // ...
	 // if custom error, display validationMessage
	 if (validity.customError) {
		return input.validationMessage;
	}
}

A bit clumsy, but it comes with an advantage: it captures textarea as well, which the normal pattern does not. Let's move on before adding the extra maxLength, to custom validation, and custom errors, so that we tuck this mess up elsewhere.

anchorCustom validation

Custom validation is set with setCustomValidity and read by validationMessage . We covered that much. But how to make it interactive, is to watch one: input and set custom validity.

We want to end up with something like this:

<OlInput placeholder="Kool">
<!-- does not work -->
	<input type="date" bind:value={formState.date} id="date" data-validate={() => isFuture()} />
</OlInput>

We cannot do that when using HTML native attributes. So we either reference the function as a string and have a lookup ready for it, create a separate attach for the input, or promote the validation to be on the wrapper. Let me try them all:

anchor1. Function lookup

If we add a direct data-validate attribute that points to a key in a map, which then defines the function, it would look like this:

<OlInput placeholder="Kool">
	<input type="date" bind:value={formState.date} id="futureDate" data-validate="future" data-error-message="Must be in the future" />
</OlInput>

Then we define the custom function that should run when validation is triggered:

// form.ts
export const InputValidators = new Map<string, any>([
  ['future', futureValidator],
  // other functions
]);

// the validation function
export const futureValidator = (value: string): boolean => {
  const today = Date.now();

  if (!value) return true;
  const _value = new Date(value);
  if (!_value || +_value > +today) {
    return true;
  }
  return false;
};

In our component, we look for that validate attribute, and trigger on input. But also, on belated validation. This way we can escape the programmatic value set silent trap.

// OnInput.svelte

const refElement = {
	// ...
	[createAttachmentKey()]: (node: HTMLInputElement | HTMLTextAreaElement) => {
		untrack(() => {
			// ...
			// upon input
			node.addEventListener('input', (e) => {
				checkValidity(node);
				errorText = ErrorMessage(<HTMLInputElement>e.target);
			});
		});
	}
};

Let's place our new function shared in form file, next to the form validation function.

// form.ts
// a check validty function to call at the right time
const checkValidity = (node) => {
	// check validation data attribute
	const dataValidate = node.dataset?.validate;
	// if exists look it up, then pass the validation error from somewhere
	if (dataValidate) {
		const fn = InputValidators.get(dataValidate);
		node.setCustomValidity(fn?.(node.value) ? '' : node.dataset.errorMessage || 'invalid');
	}
}
export const ValidateForm = (form: HTMLFormElement, toast: boolean = true): boolean => {
 form.classList.add("was-validated");
 // try individual elements, find the ones with data-validate
  const _inputs = form.querySelectorAll('[data-validate]');
  if (_inputs) {
    _inputs.forEach((input: HTMLInputElement) => {
      checkValidity(input);
    });
  }
  // then check as normal
  if (!form.checkValidity()){
      return false;
  }
}

If we left this out to Steve (our dev ops AI agent), it, he, would probably just dump it anywhere.

anchor2. Separate attachment

Using a string to lookup a function may not be ideal, the other option is its own attachment. Let's create a new attachment in its own file. Yes Stevie, in its OWN file.

// validate.attach.ts

const _checkValidity = (node: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, validator: (v: any) => boolean) => {
  // if exists look it up, then pass the validation error from somewhere
  if (validator) {
    node.setCustomValidity(validator?.(node.value) ? '' : node.dataset.errorMessage || 'invalid');
  }
};


export function olvalidate(validator: ((v: any) => boolean)): Attachment {
  return (element: HTMLInputElement) => {
    element.addEventListener('input', (_) => {
      _checkValidity(element, validator);
    }, {capture: true});

    // also catch form submission to revalidate
    if (element.form) {
	    // this is too late though
      element.form.addEventListener('submit', (_) => {
        _checkValidity(element, validator);
        // with capture, it kicks in first
      }, {capture: true});
    }
    return () => {
      // stop listning... later
    };
  };

};

There is of course the edge case, if the element is programmatically updated, form Validate function is called before the Attachment form submission, missing the update. This is also the case with element validation. The component Error message is set before the custom validation kicks in. That kind of sucks. To override this behavior, we let the element capture both events. Then apply the attachment to the input:

  <OlInput placeholder="Date" >
    {#snippet input(ref)}
			<input {...ref} type="date" bind:value={formState.futureDate} id="futureDate" {@attach olvalidate(futureValidator)} data-error-message="Must be in the future"  />
		{/snippet}
	</OlInput>

There is another hidden corner to that, and that is our ValidateForm function may run without form submission. There is another twist we can add here:

Attachment with custom events

If we, instead of watching element.form.onsubmit, watch a custom event, we can control when that event fires.

// validate.attach
export function olvalidate(validator: ((v: any) => boolean)): Attachment {
	return (element: HTMLInputElement) => {
		// remove element.form listenered, and add
		element.addEventListener('olvalidate', () => {
      _checkValidity(element, validator)
    });
	};
};

Then upon validation

// form.ts

export const ValidateForm = (form: HTMLFormElement, toast: boolean = true): boolean => {

  form.classList.add("was-validated");

	// dispatch
  Array.from(form.elements).forEach((el) => el.dispatchEvent(new CustomEvent('olvalidate')));
  
  // this does the rest
  if (!form.checkValidity()){
		return false;
  }
  return true;
};

Passing parameters

One more addition, is passing the node itself, or a list of parameters.

// validator.attach

// pass the node itself
const _checkValidity = (node, validator) => {
  // pass node as is
  if (validator) {
    node.setCustomValidity(validator?.(node) ? '' : node.dataset.errorMessage || 'invalid');
  }
};

// then the validation function read anything off of node
export const futureValidator = (node): boolean => {
	// read node.value
}

This might be a stretch, the simpler way is to pass arguments instead of node, like this


// keep passing the node.value to _checkValidity, but define validation function with extra params:
export const someParamValidator = (v: any, params?: {min: number, max: number}): boolean => {
  // read params for validation, example:
  if (v.length < params.min) return false;
 
  return false;
};

Then to use it like this:

{@attach olvalidate((v) => someParamValidator(v, {min: 3, max: 6}))}

anchor3. Promote to wrapper

The last approach is to promote validation to be a component function, instead of an input attachment, and in order to control the validation from the outside, we create custom events. (Custom events are the opposite of emitting events, it is watching a trigger from the outside world.)

// OlInput.svelte

const { validate, errorMessage /*...*/ }: { validate?: (value: any) => boolean; errorMessage?: string } = $props();

const checkValidity = (node) => {
	// check validation data attribute
	node.setCustomValidity(validate?.(node.value) ? '' : errorMessage || 'invalid');
};

const refElement = {
	 [createAttachmentKey()]: (node: HTMLInputElement | HTMLTextAreaElement) => {
		untrack(() => {
			 
				// ...
			node.addEventListener('invalid', (e) => {
          errorText = ErrorMessage(<HTMLInputElement>e.target);
			});
			node.addEventListener('input', (e) => {
				// on input check validity
				if (validate) {
					  checkValidity(node)
				}
				errorText = ErrorMessage(<HTMLInputElement>e.target);
			});
			// catch custom event as well
			node.addEventListener('olvalidate', (e) => {
				if (validate) {
					checkValidity(node);
				}
				// no need to call ErrroMessage, the invalid listner will do that
			});
	
	   });
		});
	 }
}

So we keep the custom event firing upon form validation, and now this is how it looks like in HTML

<OlInput placeholder="Date" validate={(v) => futureValidator(v)}  errorMessage="Must be in the future" >
	{#snippet input(ref)}
		<input {...ref} type="date" bind:value={formState.futureDate} id="futureDate" />
	{/snippet}
</OlInput>

Passing parameters back is exactly the same way:

validate={(v) => someParamValidator(v, {min: 3, max: 6})}

This too works as expected. I would rather use only one method of the three. The first one is too loose, I'd drop it. The second and third are almost identical. Let's see how other scenarios rate against them. What we need is a way to handle more than one validation function, and show different messages when either validation fails. That isn't a single validator. Can we pull it off?

That, in addition to validating checkboxes, selects and other types, is next Tuesday. I know it isn't exactly Tuesday every time, but who's watching? Besides Steve? 😴

  1. 28 days ago
    Programmatic attachment in Svelte
  2. 12 days ago
    Native Validation
  3. two days ago
    Custom validation and a bit of a fig leaf
Have a comment?
Tweet sekrabbin.
Subscribe to Sekrab Parts newsletter.