Today I'm happy to announce the release of Svelte Formula - a new forms
library for Svelte.
Formula is a Zero-Config
library - what this means is that you do not have to pass any settings to the library itself to handle form validation and submission - it uses the validation properties of HTML5 forms directly, meaning you can create progressive, accessible forms first.
The library is for use with the use directive and can be bound to any element, not just <form>
ones and the library automatically handles subscription and unsubscription to any form element with a name
attribute.
Here is the example from the demo:
<script>
import {onDestroy} from 'svelte';
import {formula} from 'svelte-formula@0.0.5'
const {form, formValues, validity, touched, formValid} = formula();
const sub = formValues.subscribe(v => console.log(v));
onDestroy(() => {
sub();
})
</script>
<form use:form>
<div class='form-field'>
<label for='username'>Username</label>
<input type='text' id='username' name='username' required minlength="8" class:error={$touched?.username &&
$validity?.username?.invalid}/>
<div hidden={$validity?.username?.valid}>{$validity?.username?.message}</div>
</div>
<div class='form-field'>
<label for='password'>Password</label>
<input type='password' id='password' name='password' required minlength="8" class:error={$touched?.password &&
$validity?.username?.invalid}/>
<div hidden={$validity?.password?.valid}>{$validity?.password?.message}</div>
</div>
<button disabled={!$formValid}>Save</button>
</form>
<style>
.form-field {
margin-bottom: 10px;
border-bottom: 1px solid lightgrey;
}
.error {
border: 1px solid red;
}
</style>
In this example the only validations are required
and minlength
applied directly to the HTML element itself - displaying errors and error states are via the validity
object and the touched
object allows us to only apply it when the form element is first focused on.
The release is considered an alpha
version - the API may change and there are still tests and documentation to right - but you can try it our right now in your own project with npm install svelte-formula
- any bugs, issues or suggestions please feel free to leave them here
Top comments (0)