chainlist / svelte-forms Goto Github PK
View Code? Open in Web Editor NEWSvelte forms validation made easy
License: MIT License
Svelte forms validation made easy
License: MIT License
Could we add support for adding errors directly into the fields somehow?
A typical use case would be to handle errors from an API after it has been called.
My code looks like this:
import { form, field } from 'svelte-forms';
import { required, pattern } from 'svelte-forms/validators';
const firstname = field('firstname', '', [required(), pattern(/^[a-z ,.'-]+$/i)], {
valid: false
});
const lastname = field('lastname', '', [required(), pattern(/^[a-z ,.'-]+$/i)], {
valid: false
});
const personalForm = form(firstname, lastname);
And I'm getting this error after deployment. It works fine on dev server:
500
Must use import to load ES Module: /var/task/node_modules/svelte-forms/index.js
require() of ES modules is not supported.
require() of /var/task/node_modules/svelte-forms/index.js from /var/task/.netlify/server/entries/pages/index.svelte.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /var/task/node_modules/svelte-forms/package.json.
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/node_modules/svelte-forms/index.js
require() of ES modules is not supported.
require() of /var/task/node_modules/svelte-forms/index.js from /var/task/.netlify/server/entries/pages/index.svelte.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /var/task/node_modules/svelte-forms/package.json.
I was just installing the latest version of svelte-forms (thanks for the PR merge!) and incidentally realized that alongside svelte-forms a number of other (unrelated) dependencies got installed, like
A couple of them are even nowhere used.
And after inspecting the installed package I saw that there is a lot of stuff in there that is not actually related with the library at all.
Here are two screenshots of all the installed files, as I see it only the green marked files are actually neccessary for someone consuming this library...
I would not be surprised if the issues described in #48, #55 and #58 are somehow related to the abundance of configuration files and superfluous resources.
I have a simple sveltekit with tailwind page and I'm trying to do a simple signUp form with all the form fields required() . The thing is that the valid value of the form starts as true when all the values of the fields are empty and whenever a field is valid and the others are empty the value of form.valid is true.
<script lang="ts">
import { form, field, style } from 'svelte-forms';
import { required, email, matchField } from 'svelte-forms/validators';
const userEmail = field('email', '', [required(), email()]);
const password = field('password', '', [required()]);
const confirmPassword = field('passwordConfirm', '', [required(), matchField(password)]);
const signUpForm = form(userEmail, password, confirmPassword);
</script>
<label for="email" class="label">Email</label>
<input
type="text"
placeholder="Type your email"
name="email"
bind:value={$userEmail.value}
/>
<label for="password" class="password">Password</label>
<input
type="password"
placeholder="Type your password"
name="password"
bind:value={$password.value}
/>
<label for="confirmPassword" class="confirmPassword">Confirm password</label>
<input
type="confirmPassword"
placeholder="Confirm your password"
name="confirmPassword"
bind:value={$confirmPassword.value}
/>
I expected the inital value of the form.valid
to be false on initialization and whenever for it to depend on the validity of the fields even when they are not dirty
In both cases the $form.valid
should be false right?
submit
buttonsubmit
button is disabled unless the form (all fields) are validvalid
& dirty
form.validate()
to make the form invalid so the submit
button is disabledform.validate()
, all fields are flagged as dirty and the error messages are shown (which i only want once the field has been touched)Once solution i could imagine is:
form.validate()
submit
if !form.valid || anyField.isDirty
form()
failed due incorrect typescript types.Also i don't understand why the initial form comes up as valid
and dirty
...!?
Any idea how i can achieve what i want ?
Hi how do we access all the values at once to submit the values ?
i.e:
myForm.values() ?
How does validation work with checkbox inputs?
I'm using a simple login form with the following:
const userEmail = field("userEmail", "", [email()], {
validateOnChange: true,
valid: false,
});
const password = field("password", "", [min(1)], {
validateOnChange: true,
valid: false,
});
However, regardless of what I put in for email and check for {#if $loginForm.hasError("userEmail.email")}, i never get a validation error for email.
The password generates the error correctly when I use {#if $loginForm.hasError("password.min")}.
Right now summary()
works great, but you can't subscribe to it.
I would like to add a validator that checks the values of two fields and ensures that they match, as you would when entering and confirming a new password, for example.
Is there a way to do this, or if not, is this a feature that could be added?
Is the V2 only targeted for SvelteKit? I hope its not an overkill for svelte only SPA.
When the <input> fields are not wrapped in <form> browser warns about missing form tag like
[DOM] Password field is not contained in a form
when <form> tag is used, Svelte warns about:
Plugin svelte: <form> will be treated as an HTML element unless it begins with a capital letter
Please suggest a way to fix/workaround this.
It seems that this project has no licensed defined. I think this makes it hard to choose the lib for os or commercial projects.
How can I set a value imperatively for example in a reactive statement? This won't work because svelte-forms expects a Field from me. I just want to set the value.
const name = field('name', undefined);
const _form = form(name);
$: name.set($someValueFromExternal); // Doesn't work
$: $name = $someValueFromExternal; // Doesn't work
Is your feature request related to a problem? Please describe.
Currently the documentation of min
and max
validators does not specify what is the behavior when a non-number value (NaN
) is provided. Users may think these validators accept only numbers as valid input, but in case of a non-number the function validates its length.
Describe the solution you'd like
It would be helpful to have this explicitly stated in the documentation of min
and max
.
Additional context
On a side not, it might be nice to have a validator for "input is a number" (though one can get that with a pattern validator).
When submitting a form, it is neccessary to access the data that has been entered in any field.
If I get this correctly, currently it is neccessary to access each field individually to construct a form state.
It would be nice to have a way of accessing the complete state at once.
Maybe something like:
<script>
const firstName = field('firstName', '', [required()], { checkOnInit: true });
const lastName = field('lastName', '', [required()], { checkOnInit: true });
const myForm = form(firstName, lastName)
function onSubmit() {
console.log('form has been submitted, current state: ', $myForm.state())
}
</script>
<input type="text" bind:value={$firstName.value} />
[...]
<button on:click={onSubmit}>submit</button>
Let me know if this sounds something you'd be interested in, I'd like to try my luck on a PR!
I think I spotted an error in the example for combined.
It has
const myForm = form(name);
which I believe should be const myForm = form(fullname);
And the same thing for the button in the example, it has:
on:click={name.validate}
which I believe should be on:click={fullname.validate}
Hi!
I'm using combined function to integrate the indicative number and phone number and $myForm.dirty is true just after DOM renders my page.
I need to do validations with dirty attribute since the form is a generic component for my app.
Thanks for read me and i hope the solution could be created soon :)
When using an async validator, text inputs can experience stuttering while typing. For example, displaying an error when a username is already taken requires making a request to see whether the inputted username is valid or not. I'm not sure what the exact cause is, but it makes it very hard to use async validators.
A potential fix could consist of either debouncing any async validators or canceling any pending promises in favor of evaluating a newer one. For now, I'll just use external validation on the input to check if the username is taken or not.
Describe the bug
When validateOnChange
is false
then when the field store changes, processField
is called with []
as validations
. This causes valid
in line 49 of createFieldStore.js
to be trivially true
, and the field is seen as valid until manual validation (even when it's value is invalid).
To Reproduce
validateOnChange
as false
, and some validatorvalid
in fieldExpected behavior
valid
should remain false
until the value is validated
Additional context
The issue resolves by changing the if
in createFieldStore.js
line 47 to be:
if (validations && validations.length > 0)
But I think it might be cleaner to pass a null
or some other value instead of []
in line 75, to make it explicit that no validation should occur and to distinguish between the case where the validators array is purposefully empty.
Currently the call is:
_set(processField(field, [], { dirty: true }));
Could be:
_set(processField(field, null, { dirty: true }));
@chainlist Hi, thanks for this helper library to get validation done in Svelte.
I am using this library in Sapper. It works, but the form is valid although i have not entered anything. Only when I start to enter my email address the button becomes disabled.
<script>
import { form, bindClass } from 'svelte-forms';
let name = '';
const myForm = form(() => ({
name: { value: name, validators: ['required'] }
}));
</script>
<style>
:global(input.invalid) {
border-color: red;
}
</style>
<form>
<input
type="text"
name="name"
bind:value={name}
use:bindClass={{ form: myForm }} />
<button disabled="{!$myForm.valid}">Login</button>
</form>
Note: as soon as I load the page, the button is disabled briefly and then active again
It seems the initCheck function does not work properly
How can i solve this?
Steps to Reproduce: make 2 inputs. make both required. make the first valid, then make it invalid. then make the second valid. the whole form will show as valid.
Expected Behavior: the whole form should be invalid. I think this is likely because it's only checking changed inputs, but not persisting the previous invalid states. There should be an option to re-check every input every time, or make this the default.
I need to set field value programatically, but sometimes the value is null or undefined.
// example
const name = field('name', '');
name.set(null);
If I call set method with null parameter it causes this error:
TypeError: Cannot convert undefined or null to object
It is caused by const keys = Object.keys(field);
in function isField .
Is it feature or bug?
I can work around it with this:
const fieldObj = get(name);
fieldObject.value = null;
name.set(fieldObj);
But it seems unnecessarily complicated.
checkOnInit
does not seem to marking a form
or a field
in the form
as invalid on initial render when checkOnInit
is true.
https://svelte.dev/repl/1d6d64e61cfe4f1788fe3627bb27a690?version=3.44.3
Also notice that if validateOnChange
is not set in options when checkOnInit
is set to true
, it does not seem to re-validate thefield
. As in, in a dirty state, if a text field with required
is set back to falsy, field
is not marked as invalid. May be expected behavior as I don't see validateOnChange
or similar options being defaulted in createFieldStore
.
https://svelte.dev/repl/f6915e493d574d3c91ac9759701f650e?version=3.44.3
Is your feature request related to a problem? Please describe.
If, for example, a field representing a checkbox has its value change from true
to false
, back to true
again, I'd like to end up with dirty = false
for that field. In that case, submitting or resetting the form wouldn't change anything, so I'd like to know to keep those operations disabled.
Describe the solution you'd like
Is there perhaps already an option for this behavior, or a workaround?
Currently, a field is marked as dirty only when its value has changed; but I want it to be marked dirty when its been focused.
Hey... I wanted to use this in my project but cannot. Still it is a good tool. Idk if u want to do this, but i'll propose anyway
Would be nice if u can do operations on inputs. eg 3+5*(2) etc... see expr-eval: https://www.npmjs.com/package/expr-eval
Think about it
This seems interesting, but the examples are not working
Describe the bug
Some links in the documentation are identical and lead to the wrong section. For example the functions
under COMBINED
leads to functions
under FORM
. This happens with several links (options
and example
).
To Reproduce
Steps to reproduce the behavior:
functions
under COMBINED
FORM
Expected behavior
Links should point to subsections in their correct respective section
Getting the following error with [email protected] and @sveltejs/[email protected]
Cannot find module '/Users/.../node_modules/svelte-forms/form' imported from /Users/.../node_modules/svelte-forms/index.js
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/.../node_modules/svelte-forms/form' imported from /Users/.../plate-svelte-kit/node_modules/svelte-forms/index.js
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:416:11)
at moduleResolve (node:internal/modules/esm/resolve:932:10)
at defaultResolve (node:internal/modules/esm/resolve:1044:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
at link (node:internal/modules/esm/module_job:75:36)
can be reproduced by creating a new sveltekit project using npm init svelte@next my-app
, installing, opting to use typescript and trying to use svelte-forms
Is there a way to check validation of all form inputs whatever I change any of them?
Is your feature request related to a problem? Please describe.
I have two fields that get validated only on:blur
. There is a combined field comprised of the other two, that performs additional validation of the two fields. Since the combined field validators are called whenever there is any change in the two fields, it is as if the two are checked on:change
, which results unwanted and unnecessary validations (and many API requests).
Describe the solution you'd like
Would be great to have an option like manualValidation
in combined fields to only validate manually. So when that option is enabled, validation will occur only when explicitly called. As a default it should probably be false
.
Additional context
If this is implemented, perhaps it should come with a valid
option for combined fields, so one could set valid
to false
and with that make sure that manual validation must be called for the combined field.
Is your feature request related to a problem? Please describe.
Right now, when you reset()
fields which have an initial value, they get reset to that initial value, which makes sense. But if I want to load in initial values as safe defaults but have them conveniently cleared away this is currently impossible except by setting the values programmatically when the form loads.
Describe the solution you'd like
I'd like to have field.clear()
and form.clear()
which set the field or form to an empty value, rather than the initial value.
Describe alternatives you've considered
Setting the values when I first load the inputs and use .reset()
instead.
Thanks for the great looking svelte library! I'm pretty new to svelte but struggling to setup a form using this library.
I have a form which I don't want to be validated until myForm.validate();
is called. I pass in initCheck: false,
and this works as expected but use:bindClass={{ form: myForm }}
seems to not work as intended when the required validator is used. When the field becomes empty, the input loses it's dirty
class but keeps it's valid
class despite being a required field. Any idea what's going on?
Is your feature request related to a problem? Please describe.
Currently, it seems that there is no way to programmatically iterate over validation errors and print a custom error message for each. In the documentation, an {#if}
statement is used to print errors one by one.
{#if $myForm.hasError('name.required')}
<div>Name is required</div>
{/if}
It's possible for users to maintain an additional object that maps a validator's name to a custom error message, but that is rather cumbersome and "boilerplatey".
Describe the solution you'd like
Add an optional errorMessage
property to the object returned by the (inner) validation function in Validator
. The type of the property could be () => string | string
. This would allow one to programmatically generate custom error messages based on current input value at the time of validation (or static messages as well).
Describe alternatives you've considered
Provide a separate object that maps each validator name to an (optional) error message (which is of type () => string | string
). This has the benefit of not requiring a change in the signature of Validator
. An additional method could be included that iterates over current error messages. A drawback is that it relies on the user entering unique names to validators (not sure if that might already be the case?).
Additional context
There is currently a pull request (#50) by @eden-omb that relates to a similar issue. From what I understand, they suggest to use the name
property to pass informative errors. This would be helpful but has three main issues:
name
of Validator
as a key in their own objects that need a string key. Validation error messages are not always unique, and it's probably preferable not to use error messages as keys.between(5, 10, "Must be between 5 and 10")
cannot have a message such as: 4 is not between 5 and 10
.name
and not, for example, errorMessage
.It looks nice, but how to make it work on button click?
I tried this:
use:bindClass={{ form: checkoutForm, name: 'shipping_lastname', valid: 'validation-passed', invalid: 'validation-failed'}}
But validation starts instantly when user starts to enter input value. Also, this code adds invalid class to other empty inputs in the form. Can someone help please and tell me how can i make same behaviour, but only after button click? Thanks
"Function called outside component initialization" when "validateOnChange: true" but works if "validateOnChange: false" .
But, "validateOnChange: false" is useless.
If checkOnInit option of field()
function is set to true, the initial validation immediately sets dirty
flag to true.
The field is then marked as dirty without any user input or without manually setting a value.
Demo for demonstration: REPL demo
<script>
import { form, field } from 'svelte-forms';
import { required } from 'svelte-forms/validators';
const input1 = field('input1', '', [required()], {checkOnInit: false});
const input2 = field('input2', '', [required()], {checkOnInit: true});
input2.subscribe(console.log)
</script>
<section>
checkOnInit: false
<input type="text" bind:value={$input1.value}/>
dirty: {$input1.dirty}
<br>
checkOnInit: true
<input type="text" bind:value={$input2.value}/>
dirty: {$input2.dirty}
</section>
Hi! Thanks for what looks like a promising library.
From what I've gathered, validation takes place already when a form is mounted, so that the user is greeted by errors and corrective messages even before they've given filling in a try. I'd prefer for the validation errors to show up first when the field is blurred (i.e. the field loses focus). Do you think this sounds like a good idea?
I'd be glad to contribute something myself if you haven't got the time.
I'm running into this problem trying to use svelte-forms in a sveltekit project:
Failed to resolve entry for package "svelte-forms". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "svelte-forms". The package may have incorrect main/module/exports specified in its package.json.
I've simply yarn add
ed svelte-forms and put import { form } from 'svelte-forms';
in a component.
I'm just running using yarn run dev
My project also has typescript.
Currently it shows error even on empty form, before user entered anything even with initCheck: false. How I can make it start validating field only after user typed something there? I still need validation during user input, but not before first input.
Describe the bug
The min validator can not be used for a text field where you want n characters and they input a number > n.
To Reproduce
Steps to reproduce the behavior:
Expected behavior
I believe a specific minLength / maxLength validator is required for this situation, as I want the validator to only validate the number of characters in the text and not the potential number value.
I typically make extensive use of the dirty attribute when validating forms, e.g. a field cannot be invalid unless it is dirty. However this is hard to achieve with only a form-level dirty attribute. dirty
does appear to exist on each field's validation object, but it references the form as a whole, so all field-level dirty
attributes change together.
Am I missing this functionality somewhere? Or would others see this as a valuable addition to the library?
Hi,
I've downloaded svelte-forms for a personal project directly from NPM and got the version : 1.2.0
.
Having a bug in this version with async validations, I have found the problem and fixed it inindex.js
:
if (!valid) {
n.fields[fieldName].errors.push(rule); // <== should be name
}
Then, I have planned to fix directly in this repo but I found two problems :
package.json
refers to the version 1.0.1 and there is no reference to the version 1.2.0 from NPM 🤔In conclusion, I have no idea how to deal with this situation... => The NPM package seems late compared to the repo but if I look the package version, it's the contrary :/
=> Time to reboot to an identical version 1.3.0 on NPM and on Github...? 😉
Thanks in advance for your answer,
Alexandre
I have a form with four fields:
const myForm = form(() => ({
companyName: { value: companyName, validators: ['required'] },
firstName: { value: firstName, validators: ['required'] },
lastName: { value: lastName, validators: ['required'] },
email: { value: email, validators: ['required', 'email'] },
}));
const submit = e => {
if (!$myForm.valid) {
return;
}
};
<form on:submit={submit}>
<label>
<h4>Företag</h4>
<input
placeholder="Företagsnamn"
type="text"
name="companyName"
bind:value={companyName}
use:bindClass={{ form: myForm }} />
</label>
<label>
<h4>Dina uppgifter</h4>
<input
placeholder="Förnamn"
type="text"
name="firstName"
bind:value={firstName}
use:bindClass={{ form: myForm }} />
</label>
<label>
<input
placeholder="Efternamn"
type="text"
name="lastName"
bind:value={lastName}
use:bindClass={{ form: myForm }} />
</label>
<label>
<input
placeholder="E-post"
type="text"
name="email"
bind:value={email}
use:bindClass={{ form: myForm }} />
</label>
<button type="submit" disabled="{!$myForm.valid}">Login</button>
</form>
However, it seems the form considers itself valid if only one field is filled out:
Have I missed something?
6:31:56 PM [vite] new dependencies found: svelte-forms, svelte-forms/validators, updating...
> node_modules/websocket/lib/WebSocketRouter.js:18:19: error: Could not read from file: /workspace/transport-app/util
18 │ var util = require('util');
╵ ~~~~~~
> node_modules/websocket/lib/WebSocketRouter.js:19:27: error: Could not read from file: /workspace/transport-app/events
19 │ var EventEmitter = require('events').EventEmitter;
╵ ~~~~~~~~
> node_modules/websocket/lib/WebSocketRequest.js:17:21: error: Could not read from file: /workspace/transport-app/crypto
17 │ var crypto = require('crypto');
╵ ~~~~~~~~
> node_modules/websocket/lib/WebSocketRequest.js:19:18: error: Could not read from file: /workspace/transport-app/url
19 │ var url = require('url');
╵ ~~~~~
> node_modules/node-gyp-build/index.js:3:17: error: Could not read from file: /workspace/transport-app/os
3 │ var os = require('os')
╵ ~~~~
> node_modules/websocket/lib/WebSocketClient.js:22:20: error: Could not read from file: /workspace/transport-app/https
22 │ var https = require('https');
╵ ~~~~~~~
> node_modules/node-gyp-build/index.js:1:17: error: Could not read from file: /workspace/transport-app/fs
1 │ var fs = require('fs')
╵ ~~~~
> node_modules/websocket/lib/WebSocketClient.js:21:19: error: Could not read from file: /workspace/transport-app/http
21 │ var http = require('http');
╵ ~~~~~~
> node_modules/node-gyp-build/index.js:2:19: error: Could not read from file: /workspace/transport-app/path
2 │ var path = require('path')
╵ ~~~~~~
> node_modules/websocket/vendor/FastBufferList.js:7:21: error: Could not read from file: /workspace/transport-app/buffer
7 │ var Buffer = require('buffer').Buffer;
╵ ~~~~~~~~
> node_modules/node-fetch/lib/index.mjs:6:17: error: Could not read from file: /workspace/transport-app/zlib
6 │ import zlib from 'zlib';
╵ ~~~~~~
> node_modules/node-fetch/lib/index.mjs:1:19: error: Could not read from file: /workspace/transport-app/stream
1 │ import Stream from 'stream';
╵ ~~~~~~~~
> node_modules/websocket/node_modules/debug/src/node.js:5:18: error: Could not read from file: /workspace/transport-app/tty
5 │ var tty = require('tty');
╵ ~~~~~
> node_modules/websocket/node_modules/debug/src/node.js:193:24: error: Could not read from file: /workspace/transport-app/net
193 │ var net = require('net');
╵ ~~~~~
6:31:56 PM [vite] error while updating dependencies:
Error: Build failed with 14 errors:
node_modules/node-fetch/lib/index.mjs:1:19: error: Could not read from file: /workspace/transport-app/stream
node_modules/node-fetch/lib/index.mjs:6:17: error: Could not read from file: /workspace/transport-app/zlib
node_modules/node-gyp-build/index.js:1:17: error: Could not read from file: /workspace/transport-app/fs
node_modules/node-gyp-build/index.js:2:19: error: Could not read from file: /workspace/transport-app/path
node_modules/node-gyp-build/index.js:3:17: error: Could not read from file: /workspace/transport-app/os
...
at failureErrorWithLog (/workspace/transport-app/node_modules/esbuild/lib/main.js:1451:15)
at /workspace/transport-app/node_modules/esbuild/lib/main.js:1131:28
at runOnEndCallbacks (/workspace/transport-app/node_modules/esbuild/lib/main.js:921:63)
at buildResponseToResult (/workspace/transport-app/node_modules/esbuild/lib/main.js:1129:7)
at /workspace/transport-app/node_modules/esbuild/lib/main.js:1238:14
at /workspace/transport-app/node_modules/esbuild/lib/main.js:609:9
at handleIncomingPacket (/workspace/transport-app/node_modules/esbuild/lib/main.js:706:9)
at Socket.readFromStdout (/workspace/transport-app/node_modules/esbuild/lib/main.js:576:7)
at Socket.emit (node:events:390:28)
at Socket.emit (node:domain:475:12)
Cannot read properties of null (reading 'required')
TypeError: Cannot read properties of null (reading 'required')
at eval (/src/routes/owners/index.svelte:62:78)
at Object.$$render (/workspace/transport-app/node_modules/svelte/internal/index.js:1684:22)
at Object.default (root.svelte:38:46)
at eval (/src/routes/__layout.svelte:39:117)
at Object.$$render (/workspace/transport-app/node_modules/svelte/internal/index.js:1684:22)
at root.svelte:36:44
at $$render (/workspace/transport-app/node_modules/svelte/internal/index.js:1684:22)
at Object.render (/workspace/transport-app/node_modules/svelte/internal/index.js:1692:26)
at render_response (file:///workspace/transport-app/node_modules/@sveltejs/kit/dist/ssr.js:481:28)
at async respond$1 (file:///workspace/transport-app/node_modules/@sveltejs/kit/dist/ssr.js:1334:10)
The validator for min is not working the expected way.
If used for a string it should be invalid, if the length of the string is lower then the requirement.
But typing in just a higher number into a type="text" field, holding a string var, makes the field valid.
Example:
<script>
let abc="";
const theform = form(() => ({
abc: { value: abc, validators: ["min:5"]},
}));
</script>
<input type="text" name="abc" bind:value={abc} use:bindClass={{ form: theform }} />
{#if $theform.fields.abc != undefined && $theform.fields.abc.valid == false}
<div>ABC should be at least 5 characters long</div>
{/if}
If I just type into the field the number 6, the field is valid and the error disappears.
Validator email doesn't work
this will not work:
$myForm.hasError('name.email')
this will work:
$myForm.hasError('name.not_an_email')
See example of this issue with solution
The documentation for the email validator differs from code.
Documentation :
email
function email() => { valid: boolean, name : 'email' };
import { field } from 'svelte-forms';
import { email } from 'svelte-forms/validators';
const name = field('name', '', [email()]);
Code :
../node_modules/svelte-forms/validators
export function email() {
return (value) => {
const regex = /^[a-zA-Z0-9_+&*-]+(?:\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,7}$/;
return { valid: Boolean(value) && regex.test(value), name: 'not_an_email' };
};
}
Since we have different names this validator can not work as explained in documentation.
From my point of view there are two possible solutions:
While building the Client side SPA using Svelte (not SvelteKit), I get following error:
[rollup-plugin-svelte] The following packages did not export their "package.json" file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.
- is-promise
My app however still works. Please suggest if there's a way to fix this.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.