Published: Feb 13, 2021
(last updated: Feb 13, 2021)
| ~ 400 words
| ~ 2 minutes reading time
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<script>
import {onDestroy} from 'svelte';
import {formula} from '[email protected]'
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