npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@radicalbit/formbit

v1.2.1

Published

Lightweight state form library

Downloads

134

Readme

Formbit

Formbit is a lightweight React state form library designed to simplify form management within your applications. With Formbit, you can easily handle form state, validate user input, and submit data efficiently.

NPM license

Table of contents

Features

  • Intuitive and easy-to-use form state management.
  • Out of the box support for validation with yup.
  • Support for handling complex forms with dynamic and nested fields.
  • Seamless and flexible integration with React.
  • Full Typescript support.

Abstract

The concept behind Formbit is to offer a lightweight library that assists you in managing all aspects of form state and error handling, while allowing you the flexibility to choose how to design the UI. It seamlessly integrates with various UI frameworks such as Antd, MaterialUI, or even plain HTML, as it provides solely a React hook that exposes methods to manage the form's React state. The responsibility of designing the UI remains entirely yours.

Install

npm  install  --save  formbit
yarn  add  formbit

Getting started

import * as yup from 'yup';
import useFormbit from 'formbit';

const initialValues = { name: undefined, age: undefined };

const schema = yup.object().shape({
  name: yup
    .string()
    .max(25, 'Name max length is 25 characters')
    .required('Name is required'),

  age: yup
    .number()
    .max(120, 'Age must be between 0 and 120')
    .required('Age is required')
});

function Example() {
  const { form, submitForm, write, error, isFormInvalid } = useFormbit({
    initialValues,
    yup: schema
  });

  const handleChangeName = ({ target: { value } }) => { write('name', value); }
  const handleChangeAge = ({ target: { value } }) => { write('age', value); }
  const handleSubmit = () => {
    submitForm(
      (writer) => {
        console.log("Your validated form is: ", writer.form)
      }, 
      (writer) => {
        console.error("The validation errors are: ", writer.errors)
      });
    }

  return (
    <div>
      <label name="name">Name</label>
      <input
        name="name"
        onChange={handleChangeName}
        type="text"
        value={form.name}
      />
      <div>{error('name')}</div>

      <label name="age">Age</label>
      <input
        name="age"
        onChange={handleChangeAge}
        type="number"
        value={form.age}
      />
      <div>{error('age')}</div>

      <button disabled={isFormInvalid()} onClick={handleSubmit} type="button">
        Submit
      </button>
    </div>
  );
}

export default Example;

Local Development

For local development we suggest using Yalc to test your local version of formbit in your projects.

Type Aliases

Check

Ƭ Check<Values>: (json: Form, options?: CheckFnOptions<Values>) => ValidationError[] | undefined

Checks the given json against the form schema and returns and array of errors. It returns undefined if the json is valid.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (json, options?): ValidationError[] | undefined

Parameters

| Name | Type | | :------ | :------ | | json | Form | | options? | CheckFnOptions<Values> |

Returns

ValidationError[] | undefined

Defined in

index.ts:14


CheckFnOptions

Ƭ CheckFnOptions<Values>: Object

Options object to change the behavior of the check method

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

| Name | Type | | :------ | :------ | | errorCallback? | ErrorCheckCallback<Values> | | options? | ValidateOptions | | successCallback? | SuccessCheckCallback<Values> |

Defined in

index.ts:309


ClearIsDirty

Ƭ ClearIsDirty: () => void

Reset isDirty value to false

Type declaration

▸ (): void

Returns

void

Defined in

index.ts:20


ErrorCallback

Ƭ ErrorCallback<Values>: (writer: Writer<Values>, setError: SetError) => void

Invoked in case of errors raised by validation

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (writer, setError): void

Parameters

| Name | Type | | :------ | :------ | | writer | Writer<Values> | | setError | SetError |

Returns

void

Defined in

index.ts:25


ErrorCheckCallback

Ƭ ErrorCheckCallback<Values>: (json: Form, inner: ValidationError[], writer: Writer<Values>, setError: SetError) => void

Invoked in case of errors raised by validation of check method

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (json, inner, writer, setError): void

Parameters

| Name | Type | | :------ | :------ | | json | Form | | inner | ValidationError[] | | writer | Writer<Values> | | setError | SetError |

Returns

void

Defined in

index.ts:31


ErrorFn

Ƭ ErrorFn: (path: string) => string | undefined

Returns the error message for the given path if any. It doesn't trigger any validation

Type declaration

▸ (path): string | undefined

Parameters

| Name | Type | | :------ | :------ | | path | string |

Returns

string | undefined

Defined in

index.ts:39


Errors

Ƭ Errors: Record<string, string>

Object including all the registered errors messages since the last validation. Errors are stored using the same path of the corresponding form values.

Example

If the form object has this structure:

{
  "age": 1
}

and age is a non valid field, errors object will look like this

{
  "age": "Age must be greater then 18"
}

Defined in

index.ts:60


Form

Ƭ Form: { __metadata?: Object } & Object

Object containing the updated form

Defined in

index.ts:65


FormbitObject

Ƭ FormbitObject<Values>: Object

Object returned by useFormbit() and useFormbitContextHook() It contains all the data and methods needed to handle the form.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

| Name | Type | Description | | :------ | :------ | :------ | | check | Check<Partial<Values>> | Checks the given json against the form schema and returns and array of errors. It returns undefined if the json is valid. | | error | ErrorFn | Returns the error message for the given path if any. It doesn't trigger any validation | | errors | Errors | Object including all the registered errors messages since the last validation. Errors are stored using the same path of the corresponding form values. Example If the form object has this structure: json { "age": 1 } and age is a non valid field, errors object will look like this json { "age": "Age must be greater then 18" } | | form | Partial<Values> | Object containing the updated form | | initialize | Initialize<Values> | Initialize the form with new initial values | | isDirty | boolean | Returns true if the form is Dirty (user already interacted with the form), false otherwise. | | isFormInvalid | IsFormInvalid | Returns true if the form is NOT valid It doesn't perform any validation, it checks if any errors are present | | isFormValid | IsFormValid | Returns true id the form is valid It doesn't perform any validation, it checks if any errors are present | | liveValidation | LiveValidationFn | Returns true if live validation is active for the given path | | remove | Remove<Values> | This method updates the form state deleting value, setting isDirty to true. After writing, it validates all the paths contained into pathsToValidate (if any) and all the fields that have the live validation active. | | removeAll | RemoveAll<Values> | This method updates the form state deleting multiple values, setting isDirty to true. | | resetForm | ResetForm | Reset form to the initial state. Errors and liveValidation are set back to empty objects. isDirty is set back to false | | setError | SetError | Set a message(value) to the given error path. | | setSchema | SetSchema<Values> | Override the current schema with the given one. | | submitForm | SubmitForm<Values> | Perform a validation against the current form object, and execute the successCallback if the validation pass otherwise it executes the errorCallback | | validate | Validate<Values> | This method only validate the specified path. Do not check for fields that have the live validation active. | | validateAll | ValidateAll<Values> | This method only validate the specified paths. Do not check for fields that have the live validation active. | | validateForm | ValidateForm<Partial<Values>> | This method validates the entire form and set the corresponding errors if any. | | write | Write<Values> | This method update the form state writing $value into the $path, setting isDirty to true. After writing, it validates all the paths contained into $pathsToValidate (if any) and all the fields that have the live validation active. | | writeAll | WriteAll<Values> | This method takes an array of [path, value] and update the form state writing all those values into the specified paths. It set isDirty to true. After writing, it validate all the paths contained into $pathToValidate and all the fields that have the live validation active. |

Defined in

index.ts:348


GenericCallback

Ƭ GenericCallback<Values>: SuccessCallback<Values> | ErrorCallback<Values>

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Defined in

index.ts:67


InitialValues

Ƭ InitialValues: { __metadata?: Object } & Object

InitialValues used to setup formbit, used also to reset the form to the original version.

Defined in

index.ts:77


Initialize

Ƭ Initialize<Values>: (values: Partial<Values>) => void

Initialize the form with new initial values

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (values): void

Parameters

| Name | Type | | :------ | :------ | | values | Partial<Values> |

Returns

void

Defined in

index.ts:71


IsDirty

Ƭ IsDirty: boolean

Returns true if the form is Dirty (user already interacted with the form), false otherwise.

Defined in

index.ts:83


IsFormInvalid

Ƭ IsFormInvalid: () => boolean

Returns true if the form is NOT valid It doesn't perform any validation, it checks if any errors are present

Type declaration

▸ (): boolean

Returns

boolean

Defined in

index.ts:89


IsFormValid

Ƭ IsFormValid: () => boolean

Returns true id the form is valid It doesn't perform any validation, it checks if any errors are present

Type declaration

▸ (): boolean

Returns

boolean

Defined in

index.ts:95


LiveValidation

Ƭ LiveValidation: Record<string, true>

Object including all the values that are being live validated. Usually fields that fail validation (using one of the method that triggers validation) will automatically set to be live-validated.

A value/path is live-validated when validated at every change of the form.

By default no field is live-validated

Example

If the form object has this structure:

{
  "age": 1
}

and age is a field that is being live-validated, liveValidation object will look like this

{
  "age": "Age must be greater then 18"
}

Defined in

index.ts:121


LiveValidationFn

Ƭ LiveValidationFn: (path: string) => true | undefined

Returns true if live validation is active for the given path

Type declaration

▸ (path): true | undefined

Parameters

| Name | Type | | :------ | :------ | | path | string |

Returns

true | undefined

Defined in

index.ts:127


Object

Ƭ Object: Record<string, unknown>

Generic object with string as keys

Defined in

index.ts:133


Remove

Ƭ Remove<Values>: (path: string, options?: WriteFnOptions<Values>) => void

This method updates the form state deleting value and set isDirty to true.

After writing, it validates all the paths contained into pathsToValidate (if any) and all the fields that have the live validation active.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (path, options?): void

Parameters

| Name | Type | | :------ | :------ | | path | string | | options? | WriteFnOptions<Values> |

Returns

void

Defined in

index.ts:152


RemoveAll

Ƭ RemoveAll<Values>: (arr: string[], options?: WriteFnOptions<Values>) => void

This method updates the form state deleting multiple values, setting isDirty to true.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (arr, options?): void

Parameters

| Name | Type | | :------ | :------ | | arr | string[] | | options? | WriteFnOptions<Values> |

Returns

void

Defined in

index.ts:278


ResetForm

Ƭ ResetForm: () => void

Reset form to the initial state. Errors and liveValidation are set back to empty objects. isDirty is set back to false

Type declaration

▸ (): void

Returns

void

Defined in

index.ts:160


SetError

Ƭ SetError: (path: string, value: string) => void

Set a message(value) to the given error path.

Type declaration

▸ (path, value): void

Parameters

| Name | Type | | :------ | :------ | | path | string | | value | string |

Returns

void

Defined in

index.ts:175


SetSchema

Ƭ SetSchema<Values>: (newSchema: ValidationSchema<Values>) => void

Override the current schema with the given one.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (newSchema): void

Parameters

| Name | Type | | :------ | :------ | | newSchema | ValidationSchema<Values> |

Returns

void

Defined in

index.ts:181


SubmitForm

Ƭ SubmitForm<Values>: (successCallback: SuccessSubmitCallback<Values>, errorCallback?: ErrorCallback<Partial<Values>>, options?: ValidateOptions) => void

Perform a validation against the current form object, and execute the successCallback if the validation pass otherwise it executes the errorCallback

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (successCallback, errorCallback?, options?): void

Parameters

| Name | Type | | :------ | :------ | | successCallback | SuccessSubmitCallback<Values> | | errorCallback? | ErrorCallback<Partial<Values>> | | options? | ValidateOptions |

Returns

void

Defined in

index.ts:188


SuccessCallback

Ƭ SuccessCallback<Values>: (writer: Writer<Values>, setError: SetError) => void

Success callback invoked by some formbit methods when the operation is successful.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (writer, setError): void

Parameters

| Name | Type | | :------ | :------ | | writer | Writer<Values> | | setError | SetError |

Returns

void

Defined in

index.ts:197


SuccessCheckCallback

Ƭ SuccessCheckCallback<Values>: (json: Form, writer: Writer<Values>, setError: SetError) => void

Success callback invoked by the check method when the operation is successful.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (json, writer, setError): void

Parameters

| Name | Type | | :------ | :------ | | json | Form | | writer | Writer<Values> | | setError | SetError |

Returns

void

Defined in

index.ts:203


SuccessSubmitCallback

Ƭ SuccessSubmitCallback<Values>: (writer: Writer<Values | Omit<Values, "__metadata">>, setError: SetError, clearIsDirty: ClearIsDirty) => void

Success callback invoked by the submit method when the validation is successful. Is the right place to send your data to the backend.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (writer, setError, clearIsDirty): void

Parameters

| Name | Type | | :------ | :------ | | writer | Writer<Values | Omit<Values, "__metadata">> | | setError | SetError | | clearIsDirty | ClearIsDirty |

Returns

void

Defined in

index.ts:211


Validate

Ƭ Validate<Values>: (path: string, options?: ValidateFnOptions<Values>) => void

This method only validate the specified path. Do not check for fields that have the live validation active.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (path, options?): void

Parameters

| Name | Type | | :------ | :------ | | path | string | | options? | ValidateFnOptions<Values> |

Returns

void

Defined in

index.ts:222


ValidateAll

Ƭ ValidateAll<Values>: (paths: string[], options?: ValidateFnOptions<Values>) => void

This method only validate the specified paths. Do not check for fields that have the live validation active.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (paths, options?): void

Parameters

| Name | Type | | :------ | :------ | | paths | string[] | | options? | ValidateFnOptions<Values> |

Returns

void

Defined in

index.ts:229


ValidateFnOptions

Ƭ ValidateFnOptions<Values>: Object

Options object to change the behavior of the validate methods

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

| Name | Type | | :------ | :------ | | errorCallback? | ErrorCallback<Partial<Values>> | | options? | ValidateOptions | | successCallback? | SuccessCallback<Partial<Values>> |

Defined in

index.ts:319


ValidateForm

Ƭ ValidateForm<Values>: (successCallback?: SuccessCallback<Values>, errorCallback?: ErrorCallback<Values>, options?: ValidateOptions) => void

This method validates the entire form and set the corresponding errors if any.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (successCallback?, errorCallback?, options?): void

Parameters

| Name | Type | | :------ | :------ | | successCallback? | SuccessCallback<Values> | | errorCallback? | ErrorCallback<Values> | | options? | ValidateOptions |

Returns

void

Defined in

index.ts:235


ValidateOptions

Ƭ ValidateOptions: YupValidateOptions

Type imported from the yup library. It represents the object with all the options that can be passed to the internal yup validation method,

Link to the Yup documentation https://github.com/jquense/yup

Defined in

index.ts:249


ValidationError

Ƭ ValidationError: YupValidationError

Type imported from the yup library. It represents the error object returned when a validation fails

Link to the Yup documentation https://github.com/jquense/yup

Defined in

index.ts:332


ValidationFormbitError

Ƭ ValidationFormbitError: Pick<ValidationError, "message" | "path">

Defined in

index.ts:240


ValidationSchema

Ƭ ValidationSchema<Values>: ObjectSchema<Values>

Type imported from the yup library. It represents any validation schema created with the yup.object() method

Link to the Yup documentation https://github.com/jquense/yup

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Defined in

index.ts:169


Write

Ƭ Write<Values>: (path: keyof Values | string, value: unknown, options?: WriteFnOptions<Values>) => void

This method update the form state writing $value into the $path, setting isDirty to true.

After writing, it validates all the paths contained into $pathsToValidate (if any) and all the fields that have the live validation active.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (path, value, options?): void

Parameters

| Name | Type | | :------ | :------ | | path | keyof Values | string | | value | unknown | | options? | WriteFnOptions<Values> |

Returns

void

Defined in

index.ts:258


WriteAll

Ƭ WriteAll<Values>: (arr: WriteAllValue<Values>[], options?: WriteFnOptions<Values>) => void

This method takes an array of [path, value] and update the form state writing all those values into the specified paths.

It set isDirty to true.

After writing, it validate all the paths contained into $pathToValidate and all the fields that have the live validation active.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

▸ (arr, options?): void

Parameters

| Name | Type | | :------ | :------ | | arr | WriteAllValue<Values>[] | | options? | WriteFnOptions<Values> |

Returns

void

Defined in

index.ts:271


WriteAllValue

Ƭ WriteAllValue<Values>: [keyof Values | string, unknown]

Tuple of [key, value] pair.

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Defined in

index.ts:285


WriteFnOptions

Ƭ WriteFnOptions<Values>: { noLiveValidation?: boolean ; pathsToValidate?: string[] } & ValidateFnOptions<Values>

Options object to change the behavior of the write methods

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Defined in

index.ts:338


Writer

Ƭ Writer<Values>: Object

Internal form state storing all the data of the form (except the validation schema)

Type parameters

| Name | Type | | :------ | :------ | | Values | extends InitialValues |

Type declaration

| Name | Type | | :------ | :------ | | errors | Errors | | form | Values | | initialValues | Values | | isDirty | IsDirty | | liveValidation | LiveValidation |

Defined in

index.ts:297

License

MIT © [Radicalbit (https://github.com/radicalbit)]