DEV Community

Cover image for Felte: An extensible form library for Solid
Pablo Berganza
Pablo Berganza

Posted on • Updated on • Originally published at pablo.berganza.dev

Felte: An extensible form library for Solid

This article has been updated to showcase Felte 1.0

Arguably one of the most common problems front-end developers need to solve is form handling. Specially in modern web applications that require instant validation and other real-time interactions with the user. To provide the best user experience as possible, you’ll probably grab a third party form management library to help you.

In this post I am going to write about Felte, a form management library for Solid I have been working on for the past year that aims to make the basics of form handling on the front-end as simple as possible, while still allowing for it to grow more complex as your requirements grow.

This is one of three blog posts related to Felte. This one is oriented towards Felte’s integration with Solid. The other two are oriented towards Felte’s integration with Svelte and React.

Features

As mentioned above, Felte aims to make the basics of form reactivity as easy to handle as possible, while still allowing for more complex behaviours via configuration and extensibility. Its main features are:

  • Single action to make your form reactive.
  • Use HTML5 native elements to create your form. (Only the name attribute is necessary).
  • Provides stores and helper functions to handle more complex use cases.
  • No assumptions on your validation strategy. Use any validation library you want or write your own strategy.
  • Handles addition and removal of form controls during runtime.
  • Official solutions for error reporting using reporter packages.
  • Supports validation with yup, zod, superstruct and vest.
  • Easily extend its functionality.

How does it look like?

In its most basic form, Felte only requires a single function to be imported:

import { createForm } from '@felte/solid';

export function Form() {
  const { form } = createForm({
    onSubmit: (values) => {
      // ...
    },
  });

  return (
    <form use:form>
      <input type="text" name="email" />
      <input type="password" name="password" />
      <input type="submit" value="Sign in" />
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

We set up the form by calling createForm with our submit handler. This function returns, among other utilities, an action that can be used on your form element. Now Felte will track all inputs with a name attribute. When submitting your form, the latest values in your inputs will be passed to your onSubmit function as an object. For our previous example, the shape of values will be:

{
  email: '',
  password: '',
}
Enter fullscreen mode Exit fullscreen mode

Where can I see my data?

As you type, Felte will keep track of your user’s input in a signal that contains your form data in the same shape as the values you'd receive on your onSubmit. This signal is wrapped, allowing some extra functionality, and is returned by createForm as function called data. We'll refer to these functions as accessors from now on. When this accessor is called without any arguments (data()), it behaves like a regular signal that returns all of the form's data as an object. An argument can be passed as first argument to select a specific field, either a selector function or a string path.

For example, this would log your user’s email to the console as they type it:

// Within a component
const { form, data } = createForm({ /* ... */ });

createEffect(() => {
  // Passing a function as first argument
  console.log(data(($data) => $data.email));

  // Passing a string as first argument
  console.log(data('email'));
});
Enter fullscreen mode Exit fullscreen mode

I might need some validation here

Of course, another common requirement of forms is validation. If we want our app to feel snappy to the user, we will want some client side validation. createForm’s configuration object accepts a validate function (which can be asynchronous). It will receive the current value of your data as it changes, and it expects you to return an object with the same shape, containing your validation messages if the form is not valid, or nothing if your form is valid. Felte will keep track of these validation messages on an accessor that is returned from createForm as errors:

const { form, errors } = createForm({
  validate(values) {
    const currentErrors = {};
    if (!values.email) currentErrors.email = 'Must not be empty';
    if (!values.password) currentErrors.password = 'Must not be empty';
    return currentErrors;
  },
});

createEffect(() => {
  console.log(errors(($errors) => $errors.email));
});
Enter fullscreen mode Exit fullscreen mode

More complex validation requirements might require third party validation libraries. Felte offers first party integrations with some popular validation libraries through its extensibility features. These integrations are offered as separate packages. I will write write more about this in the next section regarding extensibility, but you can read more about these packages in our official documentation.

Handling complex scenarios via extensibility

Felte does not attempt to have the perfect solution on how to handle all scenarios regarding form management. This is why Felte offers an API to extend its functionality as your requirements grow more complex. You may have a preferred library you like to use, such as the really popular yup, or Vest (which was recently talked about during Svelte Summit). Modifying Felte’s behaviour to handle these scenarios can be done via the extend option on createForm’s configuration object. More about this can be read in the official documentation. To keep things simple for the purposes of this blog post, I am only going to write about some of the existing packages we maintain to handle some common use cases:

Validators: Integrations with popular validation libraries

We are currently maintaining four packages to integrate Felte with some popular validation libraries: yup, zod, superstruct and most recently vest. Here we will use yup as an example, but you can read more about the rest here.

The package to use yup is on npm under the name @felte/validator-yup. You will need to install it alongside yup:

npm install --save @felte/validator-yup yup

# Or, if you use yarn

yarn add @felte/validator-yup yup
Enter fullscreen mode Exit fullscreen mode

This validator package exports a function called validator which you can call with your validation schema and pass its result to the extend option of createForm:

import { validator } from '@felte/validator-yup';
import * as yup from 'yup';

const schema = yup.object({
  email: yup.string().email().required(),
  password: yup.string().required(),
});

const { form } = createForm({
  // ...
  extend: validator({ schema }), // OR `extend: [validator({ schema })],`
  // ...
});
Enter fullscreen mode Exit fullscreen mode

Reporters: Displaying validation messages

Displaying your validation messages can be done by directly using the errors accessor returned by createForm. Messages won’t be available on this accessor until the related field is interacted with.

import { Show } from 'solid-js';
import { createForm } from '@felte/solid';

function Form() {
  const { form, errors } = createForm({ /* ... */ });

  return (
    <form use:form>
      <label for="email">Email:</label>
      <input name="email" type="email" id="email" />
      <Show when={errors('email')}>
        <span>{errors('email')}</span>
      </Show>
      <button>Submit</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

If a specific field has an error, Felte assigns an aria-invalid=true attribute to the appropriate input.

But you might not like that specific syntax to handle your validation messages. Felte currently also has four accompanying packages that offer different alternatives on how to display your validation messages:

  • Using a Solid component, which gives the most flexibility and would allow you to have access to your validation messages deep within the component tree without needing to pass the errors accessor around.
  • Modifying the DOM directly by adding and removing DOM elements.
  • Using Tippy.js to display your messages in a tooltip.
  • Using the browser’s built-in constraint validation API, which can be less friendly to mobile users.

For brevity, I am only going to cover the first package. But you can read more about the rest in the documentation.

Using a Solid component to get your validation messages can be done with the package @felte/reporter-solid. You’ll need to add it to your project using your favourite package manager:

# npm
npm i -S @felte/reporter-solid

# yarn
yarn add @felte/reporter-solid
Enter fullscreen mode Exit fullscreen mode

Then you’ll need to import both the reporter function to add to the extend property, and the ValidationMessage component which you will use to receive your validation messages:

import { reporter, ValidationMessage } from '@felte/reporter-solid';
import { createForm } from '@felte/solid';

function Form() {
  const { form } = createForm({
      // ...
      extend: reporter, // or [reporter]
      // ...
    },
  })

 // We assume a single string will be passed as a validation message
 // This can be an array of strings depending on your validation strategy
  return (
    <form use:form>
      <input id="email" type="text" name="email" />
      <ValidationMessage for="email">
        {(message) => <span>{message}</span>}
      </ValidationMessage>
      <input type="password" name="password" />
      <ValidationMessage for="password">
        {(message) => <span>{message}</span>}
      </ValidationMessage>
      <input type="submit" value="Sign in" />
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

Next steps

You can check more about Felte in its official website with some functional examples. There’s also a more complex example showcasing its usage with Tippy.js and Yup available on CodeSandbox.

Finishing thoughts

I hope this served as a good introduction to Felte, and that it is interesting enough for you to give it a try. Felte is already on a stable state and used by some people. I am also open to help and suggestions so feel free to open an issue or make a pull request on GitHub.

Top comments (2)

Collapse
 
davedbase profile image
David Di Biase

Great article. I'm using Felte in Solid in 3 projects and it's such a time saver.

Collapse
 
pabloabc profile image
Pablo Berganza

I'm really glad to hear Felte has some use on the Solid side! I don't get much feedback from Solid users on GitHub so I haven't had a grasp on how useful it's been with Solid 😅.