Giter VIP home page Giter VIP logo

svelte-use-form's Introduction

  svelte-use-form

A Svelte form library that enables you to create complicated forms with minimal effort. As for Svelte, the focus is DX 💻‍✨

npm i -D svelte-use-form

GitHub package.json version npm Donate

Features:

  • Minimalistic - Don't write more than necessary.
  • No new components, bindings or callbacks required
  • Validators included and custom validator support
  • Automagically binds to inputs

Usage

It's pretty self-explanatory… check out the examples below 😉

Just make sure to prefix the form with $, when accessing its state.

Minimal Example REPL

<script>
  import { useForm, Hint, validators, minLength } from "svelte-use-form";

  const form = useForm();
</script>

<form use:form>
  <input name="title" use:validators={[minLength(5)]} />
  <Hint for="title" on="minLength" let:value>
    The title requires at least {value} characters.
  </Hint>

  <button disabled={!$form.valid}>Submit</button> <br />
</form>

or you could also print the error message like this:

...
{#if $form.title?.touched && $form.title?.errors.minLength}
  The title requires at least {$form.title.errors.minLength} characters.
{/if}

More Examples

Login Example REPL
<script>
  import {
    useForm,
    HintGroup,
    Hint,
    validators,
    email,
    required,
  } from "svelte-use-form";

  const form = useForm();
</script>

<form use:form>
  <h1>Login</h1>

  <input type="email" name="email" use:validators={[required, email]} />
  <HintGroup for="email">
    <Hint on="required">This is a mandatory field</Hint>
    <Hint on="email" hideWhenRequired>Email is not valid</Hint>
  </HintGroup>

  <input type="password" name="password" use:validators={[required]} />
  <Hint for="password" on="required">This is a mandatory field</Hint>

  <button disabled={!$form.valid}>Login</button>
</form>
Registration Example REPL
<script>
  import {
    useForm,
    Hint,
    HintGroup,
    validators,
    required,
    minLength,
    email,
  } from "[email protected]";

  const form = useForm();
  const requiredMessage = "This field is required";

  function passwordMatch(value, form) {
    if (value !== form.values.password) {
      return { passwordMatch: true };
    }
  }

  function containNumbers(numbers) {
    return function (value) {
      if (value.replace(/[^0-9]/g, "").length < numbers) {
        return { containNumbers: numbers };
      }
    };
  }
</script>

<main>
  <form use:form>
    <h1>Registration</h1>
    <label for="email">Email</label>
    <input type="email" name="email" use:validators={[required, email]} />
    <HintGroup for="email">
      <Hint on="required">{requiredMessage}</Hint>
      <Hint on="email" hideWhenRequired>This must be a valid email</Hint>
    </HintGroup>

    <label for="name">Name</label>
    <input type="text" name="name" />

    <label for="password">Password</label>
    <input
      type="password"
      name="password"
      use:validators={[required, minLength(5), containNumbers(2)]}
    />
    <HintGroup for="password">
      <Hint on="required">{requiredMessage}</Hint>
      <Hint on="minLength" hideWhenRequired let:value
        >This field must have at least {value} characters.</Hint
      >
      <Hint on="containNumbers" hideWhen="minLength" let:value>
        This field must contain at least {value} numbers.
      </Hint>
    </HintGroup>

    <label for="passwordConfirmation">Password Confirmation</label>
    <input
      type="password"
      name="passwordConfirmation"
      use:validators={[required, passwordMatch]}
    />
    <HintGroup for="passwordConfirmation">
      <Hint on="required">{requiredMessage}</Hint>
      <Hint on="passwordMatch" hideWhenRequired>Passwords do not match</Hint>
    </HintGroup><br />

    <button disabled={!$form.valid} on:click|preventDefault> Submit </button>
  </form>
  <pre>
		{JSON.stringify($form, null, 1)}
	</pre>
</main>

<style>
  :global(.touched:invalid) {
    border-color: red;
    outline-color: red;
  }

  main {
    display: flex;
    justify-content: space-around;
  }

  pre {
    height: 80vh;
    overflow: auto;
    font-size: 12px;
  }
</style>

Edge Cases REPL

API

useForm(properties: FormProperties?, formName?: string)

useForm() returns a svelte store (Observable) that is also an action. (That's what I call svelte 😆)

Why specify FormProperties?

Providing the names of the properties as arguments allows us to initialize all form controls in the form before the site is actually rendered. Thus you won't need to null-check them when accessing them.

const form = useForm({ firstName: {} });
$form.firstName // Works as expected
$form?.lastName // lastName would be null on page load

Why specify formName?

By providing a name you'll have the ability to specifically reference a form from a Hint component instead of inferring it from context.

useForm({}, "form-1") --> <Hint form="form-1"...>.

This allows you to use multiple useForm instances in a single component.

$form

Subscribe to the form with $-prefix to access the state of the form. It returns a Form instance.

Form

Remark: In reality the "Form" is an union of multiple types and its self.

class Form {
  valid: boolean;
  touched: boolean;
  values: {
    [controlName: string]: string;
  };
  reset(): void;
  [controlName: string]: FormControl | undefined;
}

FormProperties (Optional)

export type FormProperties = {
  [key: string]: {
    /** Initial value of the form control */
    initial?: string;
    /** The validators that will be checked when the input changes */
    validators?: Validator[];
    /**
     * The map through which validation errors will be mapped.
     * You can either pass a string or a function returning a new error value
     *
     * **Think of it as a translation map. 😆**
     */
    errorMap?: ErrorMap;
  };
};

FormControl

A FormControl represents an input of the form. (input, textarea, radio, select...)

Important: Every control in the form will be accessible through $form directly via the name attribute.

e.g. <input name="email" /> --> $form.email

class FormControl {
  value: string;
  touched: boolean;
  validators: Validator[];
  /** Does the FormControl pass all given validators? */
  valid: boolean;
  /** The initial value of the FormControl. */
  initial: string;
  /** The DOM elements representing this control*/
  elements: FormControlElement[];

  /** Returns an object containing possible validation errors */
  errors: ValidationErrors;
  /**
   * Contains a map of values, that will be shown
   * in place of the original validation error.
   */
  errorMap: ErrorMap;

  error(errors: ValidationErrors): void;
  /** Change the value and the value of all HTML-Elements associated with this control */
  change(value: any): void;
  /** Validate the FormControl by querying through the given validators. */
  validate(): boolean;
  /** Reset the form control value to its initial value or `{ value }` and untouch it */
  reset({ value }?: { value?: string | null }): void;
}

use:validators (Action)

Takes in the validators that should be used on the form control. e.g.

<input name="email" use:validators={[required, email]} />

<Hint></Hint>

Helper component for displaying information based on errors in an input.

Properties:

  • for="name_of_input" - Name of concerning input
  • on="error" - The error which should trigger it

Optional attributes:

  • form="form-name" - Name of the form. Defaults to form from context.
  • hideWhen="different_error" - Hides the hint if the error is active
  • hideWhenRequired - Shortcut for hideWhen="required"
  • showWhenUntouched - Display Hint even if the field hasn't been touched yet
  • let:value - Returns the value of the error

<HintGroup><Hint></Hint></HintGroup>

You can omit the Hint for property when wrapping it with a HintGroup.

Properties:

  • for="name_of_input"

Optional Properties:

  • form="form-name" - Name of the form. Defaults to form from context.

Ignore a form control

You can ignore a form control element by adding the data-suf-ignore attribute to it.

<input name="email" data-suf-ignore />

This will prevent it from being added to the form elements. And thus it won't be validated or observed for changes.

Validators

  • required
  • minLength(n)
  • maxLength(n)
  • number
  • email
  • emailWithTld
  • url
  • pattern(regExp)

Custom Validator

A validator needs to be a function that returns null if valid else an object with the key being the name of the error. The value of the object will be accessible through the error. e.g. $form.title.errors.name_of_error -> 'info'.

const passwordMatch: Validator = (value, form) => {
  return value === form.password?.value
    ? null
    : { passwordMatch: "Passwords are not matching" };
};
... use:validators={[passwordMatch]}
  or
... passwordConfirmation: { validators: [passwordMatch] } }

... $form.title.errors.passwordMatch

An example with validator.js REPL

Remarks

Chrome Autofill Solution

When Chrome autofills the form on page load, it will always register all inputs as valid. After clicking anywhere on the site, pressing a key or pressing the submit button it will then reevaluate all fields and update the state of the form.

This solution was needed due to Chrome's way of autofilling forms without actually setting the value of the inputs until the page gets a click or key event.

svelte-use-form's People

Contributors

dustinc avatar keehun avatar kyranrana avatar moalamri avatar ngtec avatar noahsalvi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

svelte-use-form's Issues

How to handle async data

Hey awesome library.
Im wondering if theres a way to handle this as I can't see anything in the demo's sorry if its there.
Im fetching data from an api and populating the fields with that data.
An issue Im running into is because the data is not set instantly.
It does not update the values in the form making them invalid
so for example here the name should have the company name value

Capture

Is there a way to force an update after fetching from the Api

Refresh validators when validators are updated

First off, great library, makes life a lot easier.

Not sure if this is viable or not, but sometimes I need to update a validator depending on a value, and it will always keep the initial value for example:

let value = 'ABC';
...
use:validators={[someValidator(value)]}
...
value = 'DEF';

Now whenever the validator run it will always use 'ABC' as the value, even though it change. I see actions support an update function for the parameters, so not sure if this is a possible solution and whether it will cause any other issues?

export function validators(
  element: FormControlElement,
  validators: Validator[]
)
  return setupValidation();

  async function setupValidation() {
    ...
    return {
        update(newValidators: Validator[]) {
          formControl.validators = newValidators;
        }
     }
  }

chromeAutofill.ts is creating a new style tag for every input in the form

Hi I've noticed chromeAutofill.ts is creating a new style tag for every text input in the form, and this is a problem for me because I am creating a new form dynamically based on a select field. In my situation it's causing the plugin to add new style tags whenever I update the select field.

isn't it a bit excessive to add the same autofill style tag for every input? Why not just add it once if it doesn't exist on the page, rather than add it for every single text input. the code doesn't change based on a input field:

@keyframes svelte-use-form-webkit-autofill {
    from {}
}

input:-webkit-autofill {
    animation-name: svelte-use-form-webkit-autofill;
}

Undefined formControl in validatorsAction

I will continue to look into this myself, but wanted to mention it here in case I am doing something blatantly wrong.

I have a form with the ability to add a new group of fields... so a repeatable dataset. The issue is that the validation bindings are not applying to the newly added fields (until saved and page refreshed).

Please see this REPL for a stripped down implementation, and to reproduce.
https://svelte.dev/repl/b0f3f08700ae451d9ddf0330049a6375?version=3.47.0

To reproduce:

  • Click Add Subform button - should see new fieldset w/ Leak Detector select field (empty select on purpose... point is to see form validation errors), and should see error message in console.
  • Click Save Form button - should see validation hint message for all Leak Detector select fields, but the one(s) added w/ Add Subform button do not.

If my implementation is incorrect, please advise. Thank you

500 - Function called outside component initialization

I am trying to use this library in sveltekit with vitejs. Everthing works fine, but when i restart the dev server, i get this error:

500
Function called outside component initialization

Error: Function called outside component initialization
    at get_current_component (/path/to/project/node_modules/.pnpm/[email protected]/node_modules/svelte-use-form/dist/index.umd.js:118:19)

What could be the reason that I get this error? Can this be solved? I have seen that this error has also already occurred in Sapper. Maybe i should use svelte for my frontend after all 😄

I use the library in my component like this:

<script>
import { useForm } from 'svelte-use-form'

const form = useForm()
</script>

or do i need to wrapp it in a onMount function?

Ignore specific input from being observed

Hi,
In my use case, I have a list that has a search input to filter the list items. Using the search input or blurring it will bind it to the form elements, which is unnecessary to the form.
What I have done as a workaround is I add an extra check to isFormMember to check if the element has id="ignore" attribute, in which it will not be considered a form element.
It works but it looks awfully wrong. I'm willing to submit a PR if there is any other suggested method to avoid adding an unwanted element to the form.

Thank you 👍

Validity is not reevaluated after variable assignment

When an <input> has bind:value={something}, updating something doesn't trigger reevaluation of the validator like it would had the field been updated by the user. Is there an event I should trigger manually to get the same user-code-paths to be fired?

Grouped CheckBoxes

Hey,
Not sure if Im using this wrong.
I can't see and example anywhere.
I'm wondering how to handle validation for grouped checkboxes.
If for example user must select at least one checkbox.
Valid seems to be reset everytime you click the checkbox vs actually checking of the group has any value not sure if that makes sense
Is this even possible to do?

I'd expect required to work on a checkbox group and pass if there is any checkboxed checked

Example here

https://www.loom.com/share/129340b652ea48dd8856a9b7ec6edf88

Thanks in advance.

feature request - add submit() form function

Probably an easy addition, but would be nice to have a submit() function since there is already a reset(). This would add the ability to programmatically run the requestSubmit() function built into JS.

J

Can't understand how to add multiple validators

I'm playing with the Repl on svelte site and I can't understand 3 things
1°) If I use the default code I don't have any error displayed for 5 minimal characters.
2°) If I remove the comments and have the

 const form = useForm({
	// 		minimalExample: { validators: [minLength(5)] }
	// }) 

I got the error if entered less than 5 char
3°) I can't find a way of adding a second validator for example maxLength = 15

Run validation on submit

Is there an example of how one would run validations on submit? I'd like to keep the submit active and allow users to click it but only proceed if no errors are present. I'd also like all the errors to show if they should be visible.

does this work with sveltekit ?

my sveltekit (which is not hte latest available) is complaining about the usage of "require" instead of import, when I do

import { useForm, Hint, validators, minLength } from "svelte-use-form";

Custom validation current field ref

Hello,

It would be nice to have access to the current field in a custom validation.

function customValidation(field, value, form) {
...
}

or

function customValidation(value, form) {
    const field = this;
}

BUG:Unable to get the value of svelte-select

I used svelte-select as select plugin
The value of svelte-select exists in a hidden input
image
image

<script>
  import Select from "[email protected]";
	import { useForm } from "[email protected]";
	const form = useForm();
  let collection = [
    { value: 1, label: "one" },
    { value: 2, label: "two" },
    { value: 3, label: "three" }
  ];
</script>

<form use:form>
	<input name="test" >
<Select name="select" items={collection} />

</form>

<pre>
{JSON.stringify($form, null, " ")}
</pre>

This is a simplified example
svelte-app.zip

Using Submit without disabled button...

I've got a problem. I don't believe my users are capable of understanding a greyed out, non operative Submit button. I really know these users, and they are confused easily. I need things simple, really simple.

I was hoping to use <input... use:validators={[required]}, then use the Hint field to display This is a Mandatory Entry for each and every mandatory question upon Button Submit. Clearly the system doesn't work that way.

Start with simple login example..

Go to Line # 19 and change <button disabled={!$form.valid}>Login</button> to <button>Login</button>

That's it. Hit the Submit button. Instead of the <Hint> element populating, what I see is the HTML5 Built-in form validation features warning popup. Image attached.
Screenshot from 2022-01-01 23-28-53

Am I doing this right? Can I get there from here? Or should I consider alternate Svelte Form Validation libraries?

Note: I've been playing with Svelte Conditional stuff...

{#if $form.login?.errors}
    <div class="customHint">This question is required.</div>
{/if}

And that's pretty much a fail. The message displays all the time. I'm trying to keep this real simple. Button groups everywhere. .touched doesn't really make any sense, so I can't really {#if $form.login?.touched && $form.login?.errors} And there is no element state for "Scrolled right on thru", sigh.

Browser compatibility?

Hi, thanks for the great library! I've been using it and wonder if it's compatible with all browsers? It seems that occasionally form.valid remains false even when all inputs have been entered. I really appreciate any help anyone can provide. Thanks!

Allow `<input>` to be empty if not required.

I have a situation where I don't require the user to input an email-address. However, if the user does input an email-address, I would like that email-address to be validated.

How can I do nothing if there is no email-address, but validate if there is one. I expected the code below to do exactly that ... however, currently the email always is validated, as if it were required.

<input
    type="email"
    name="adminEmail"
    use:validators={[email, maxLength(250)]}
    placeholder="None"
/>
<HintGroup for="adminEmail">
    <Hint on="email">Email is not valid</Hint>
    <Hint on="maxLength">Email is too long</Hint>
</HintGroup>

I'm using Version 2.4.3

Number validator is actually integers only

Hi,

I just had a look at the number validator, and it's actually only valid for integers.

It doesn't currently allow a leading dash (for negative numbers) or a decimal point.

I could make this change as a PR fairly easy since it's pretty straightforward, but it would be a breaking change. Not sure how to proceed as an additional validator really should have the name 'number' and the current implementation should be 'integer'.

Reset form

Hi @noahsalvi ,
Thanks for this library. I wish to ask how the form values can be reset. while it exposes a store, it does not expose a set or update method with which one can reset the store to , e.g an initial state

Improve validator function structure

Currently validators take in 3 arguments: value, form, control.
It could be argued that swapping form with control would make more sense. Another possibility would be to only use two parameters and have the second one be an object. That way the order would be up to the user and furthermore it would allow us to add more things later down the line without causing breaking changes.

Suggestion: add a "touch all" function to Form controls

I have a situation where I reuse a form within a Bootstrap's modal declared once in a page. This page has a list of items and the user can select one to edit its data in the form or click at a button to pass empty data to form to save a new item.

image

Each time I open modal I call $form.reset() to clean validations and read fresh data, either from selected item or new blank item. PS.: without leaving page and reusing declared form at modal.

However, if I launch a modal to fill new item data and ignore fields filling (not "touching" them and hitting submit button), validation fails and let form submit proceed as valid. I needed to add the following code before submit to proper handle validation errors:

Object
   .keys($form)
   .forEach(field => $form[field].touched = true);

Am I doing something wrong? Or the form submit is working as expected and missing a "touch all fields" function?

BTW, congrats for the amazing component.

Select field validation

Is required or custom validation supported for select fields? I tried both and couldn't get a selected option to make the form valid. It seems the custom validation function only ran once on form load instead of whenever the field changed.

Using library with components

Hi,

I tried using this with an Input component I have, but it did not work.

The reason is that the library uses use:validators={...} but Svelte complains saying Actions can only be applied to DOM elements, not components.

Can this library be used with components or am I not using it correctly?

Login test fails sometimes

When running the tests, it sometimes occurs that the login test fails.

Error:   1) tests/login.spec.ts:3:1 › Login Example =======================================================
    Error: expect(received).not.toHaveClass(expected)

    Expected string: not "touched"
    Received string: "touched"
    Call log:
      - expect.toHaveClass with timeout 5000ms
      - waiting for getByPlaceholder('password')
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"
      -   locator resolved to <input type="password" name="password" class="touched" …/>
      -   unexpected value "touched"


      11 |   await email.type("max@");
      12 |   await password.type("random pass");
    > 13 |   await expect(password).not.toHaveClass("touched");
         |                              ^
      14 |   await expect(email).toHaveClass("touched");
      15 |   await expect(button).toBeDisabled();
      16 |

        at file:///home/runner/work/svelte-use-form/svelte-use-form/tests/login.spec.ts:13:30
Notice:   1 failed
    tests/login.spec.ts:3:1 › Login Example ========================================================
  3 passed (17s)
Error: Process completed with exit code 1.

Use keys of form object

I'm quite new to TS but I think that it should be possible to use the keys of the FormProperties that is passed when initializing with const form = useForm({ username: { initial: "foo" } }); so that when accessing $form.values it knows that the only valid key is username.

If that is not possible, it would be great to at least provide some sort of generic argument to useForm so accessing an invalid key is not possible.

Custom Form Components

Hi, if I wanted to create a custom form component, how would I update the form value so validations pass?

Email validator may be insufficient?

I would love to know where the email validator regex came from.

/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(

I understand the value of keeping these regexes as small, general, and as simple as possible, but I wonder if there are different regexes that might work better. For example, maybe we can add an email2 validator that enforces the presence of a TLD. The current email validator allows email addresses like test@test or email@localhost. While those may be technically valid email addresses, I want to ensure there is a TLD for my website.

Of course, I could write my own validator, but wondered what your thoughts were on adding an alternate email validator to the library itself.

Thank you for the library! It's been such a great help for me. Thank you.

Feature Request: Provide a way to dynamically update form fields

I've been using svelte-use-form in my project, and I've encountered a scenario where I need to dynamically update a form field's value. Specifically, I am using the FileReader API to read the contents of a file input and update a textarea with the file's content.

Currently, there doesn't seem to be a straightforward way to update a form field's value programmatically. It would be helpful to have a method or a simple way to update the form field, like:

formData.content = "foo";
$form.update();

This would allow developers to update a form field's value programmatically and trigger any necessary validation checks. It would be particularly useful for scenarios where the form's state needs to be updated based on user interactions or external events, like a profile page where the user's data may be loaded after the initial form subscribe where the initial values are not available yet.

Please let me know if there are any workarounds or if this feature is already available but not documented.

Thank you for your consideration!

Custom validation typing error

Hello, I wanted to write a custom validator, using the example provided in the readme, but typescript expect a generic argument for From and I cannot understand what it needs. Could you help me please, what should be done about this? I used any as a workaround but it is not really idiomatic.
I provided a screenshot about the problem, as you can see it needs a generic argument named Keys that extends string | number | Symbol.
image

Async validators

Hello,

Thank you for this awesome project.

I would like to ask if async validators are possible? And if so, how would it be done?

display async messages coming from backend system

A often use case is to register/login users. Sometimes we need to display error messages like "Invalid Password" or something else, coming from a backend system. It would be nice, if i can use svelte-use-form to display these errors too, maybe like this:

function submit() {
   login(email, password)
      .then(() => { // do something with the response })
      .catch(e => {
         if (e.message.includes("Invalid Password")) {
            form.email.errorMap = "Wrong Password, please try again"
         }
      })
}

I don't know to what extent it is possible to store error messages in the ErrorMap that are not assigned to a validator. However, this error could then be displayed via this code dynamic:

Object.values($form.email.errors)[0]

I know the goal of this repo is to be easy to use. Nevertheless I would be happy if we could find a way to cover this use case.

Handle <select multiple>

Currently the value of a select component with the multiple is not reflected correctly in the form.

REPL for reproduction
image

Inspecting the objects, I can see that the _value in the FormControl is incorrect as well. And looking at the code, it seems that a string is always expected.

Expected:

The $form.values.foo to be an array of values.

Actual:

The first value of the array is taken as the value.

Allow an alternate method to declare validators for a field

The current method of using use:validators={} precludes being able to use children components in a form with svelte-use-form because you can't actually pass down functions as a prop—and even when the child component directly imports the validator and specifies the use:validators, it doesn't work (presumably because the use:form is in a different component?

It would be great if there was an alternate way of declaring a validator for a field so that we wouldn't have to pass down a function.

This is especially important when each field element has a lot of wrapper/other elements which normally would be wrapped in a component.

If there's already a way to do this, I would love to find out!

Set inital values, reset form and initzialize again with values

How can I set the initial values for the form?
As I understand, I cannot simply call useForm(data) where data is a plain javascript object, but have to build an object like: {name1: {initial: "myvalue}, name2: { initial: "myvalue"}}. Or how to do that programatically`

Further I tried to figure out, how to give new data to the form after initialization. Resetting works (calling $form.reset()) but assign new data with useForm() throws an error: Uncaught Error: Function called outside component initialization.
II can set a new value via $form.name.element[0].value = "value", but then reset() function will not work anymore. Using the $form.name.value setter does not reflect the value in my form.

Thank you for the clarification. Like the simplicity use-form :D.

[Feature Request] store custom error message in FormControl Class

Hi, thanks for this library to make form validation easier in svelte 👍 It is possible to integrate custom error messages in the FormControl Class?

I would imagine it like this. You can define custom error messages for each validator like this:

const form = useForm({
   email: { validators: [email, required], errors: { email: "This is not a valid email address", required: "This field is required" } }
});

the FormControl Class looks like this:

"email": {
  "errors": {
   "required": "This field is required",
   "email": "This is not a valid email address"
  },
  "valid": false,
  "touched": false,
  "validators": [
   null,
   null
  ],
  "initial": "",
  "_value": ""
 },

I might be easier to define error messages in one place and can access them, via the FormControl Object

Use boolean values for checkbox

I just started out testing the library and love its concept!
However automatic form parsing in my backend is failing as for a model with a boolean property the expected value would be true or false coming from a checkbox.

I read #10 but I'm not sure if it is necessary that the value for a checkbox is "checked" rather than true/false?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.