Performance: Form validation
Form validation affects the interaction responsiveness and visual stability during user input and form submission.
import { tick } from 'svelte'; let error = ''; let timeout; function validateInputDebounced(value) { clearTimeout(timeout); timeout = setTimeout(() => { if (value.length < 3) { error = 'Too short'; } else { error = ''; } }, 300); } <input type="text" on:input={e => validateInputDebounced(e.target.value)} bind:value={inputValue} /> {#if error} <p>{error}</p> {/if}
let error = ''; function validateInput(value) { if (value.length < 3) { error = 'Too short'; } else { error = ''; } } <input type="text" on:input={e => validateInput(e.target.value)} bind:value={inputValue} /> {#if error} <p>{error}</p> {/if}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Validate on every keystroke | Many state updates and DOM changes | Multiple reflows per input | High paint cost due to frequent updates | [X] Bad |
| Debounced validation | Fewer state updates, minimal DOM changes | Single reflow after debounce | Lower paint cost | [OK] Good |
| Add/remove error nodes | DOM nodes added/removed frequently | Reflows and layout shifts | High paint cost and CLS impact | [X] Bad |
| Toggle error visibility | DOM nodes remain, only style changes | Minimal reflows, no layout shift | Low paint cost and stable layout | [OK] Good |
bind:value={variable} to bind input values.<script>
let email = '';
let error = '';
function validate() {
if (!email) {
error = 'Email is required';
} else {
error = '';
}
}
</script>
<form on:submit|preventDefault={validate}>
<input bind:value={email} type="email" />
<button type="submit">Submit</button>
<p>{error}</p>
</form><script>
let password = '';
let error = '';
function check() {
if(password.length < 6) {
error = 'Password too short';
}
}
</script>
<form on:submit={check}>
<input bind:value={password} type="password" />
<button type="submit">Login</button>
<p>{error}</p>
</form>aria-live="polite" tells assistive tech to announce updates politely.Pass the test and this pattern moves unknown