ctrovalidate-svelte
v1.0.0
Published
Svelte adapter for Ctrovalidate.
Maintainers
Readme
ctrovalidate-svelte
Reactive form validation for Svelte.
ctrovalidate-svelte provides a useCtrovalidate function that wraps ctrovalidate-core's validation engine with Svelte stores. Returns writable and derived stores for values, errors, dirty state, and async validation status.
Installation
npm install ctrovalidate-svelte ctrovalidate-coreRequirements: Svelte >=3.0.0
Quick Start
<script lang="ts">
import { useCtrovalidate } from 'ctrovalidate-svelte';
const { values, errors, handleChange, handleBlur, validateForm, isValidating } =
useCtrovalidate<{ email: string; password: string }>({
initialValues: { email: '', password: '' },
schema: { email: 'required|email', password: 'required|minLength:8' },
});
</script>
<form on:submit|preventDefault={async () => { if (await validateForm()) { /* submit */ } }}>
<input value={$values.email} on:input={(e) => handleChange('email', e.target.value)} on:blur={() => handleBlur('email')} />
{#if $errors.email}<span>{$errors.email}</span>{/if}
<input type="password" value={$values.password} on:input={(e) => handleChange('password', e.target.value)} on:blur={() => handleBlur('password')} />
{#if $errors.password}<span>{$errors.password}</span>{/if}
<button disabled={$isValidating.email || $isValidating.password}>
{$isValidating.email || $isValidating.password ? 'Validating...' : 'Login'}
</button>
</form>API
const {
values, // Writable<T>
errors, // Writable<Partial<Record<keyof T, string>>>
isDirty, // Writable<Partial<Record<keyof T, boolean>>>
isValidating, // Writable<Partial<Record<keyof T, boolean>>>
isValid, // Readable<boolean> — derived from errors
handleChange, // (name, value) => void — updates value, marks dirty, validates
handleBlur, // (name) => void — marks dirty, validates
validateField, // (name, value?) => Promise<boolean>
validateForm, // () => Promise<boolean>
reset, // (newValues?) => void
} = useCtrovalidate<T>({
schema, // Required
initialValues, // Optional (default: {})
validateOnBlur, // Optional (default: true)
validateOnChange, // Optional (default: true)
customRules, // Optional
aliases, // Optional
messages, // Optional
locale, // Optional
});Behavior
| Call | Marks dirty | Validates |
|------|-------------|-----------|
| handleChange(name, value) | Yes | If validateOnChange |
| handleBlur(name) | Yes | If validateOnBlur |
validateFieldaborts any in-flight async rule for the same field- All
AbortControllers are aborted ononDestroy isValidis aderivedstore:truewhen no error string is truthyreset()re-initializes all stores and clears validation state
Related Packages
- ctrovalidate-core — Validation engine
- ctrovalidate-browser — Vanilla JS DOM integration
- ctrovalidate-react — React hook
- ctrovalidate-vue — Vue composable
- ctrovalidate-next — Next.js server actions
License
MIT © Ctrotech
Full documentation: https://ctrovalidate.vercel.app
