0.28.1 • Published 8 months ago

t-state-form v0.28.1

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

T-State Form

A form library based on t-state for creating controlled forms.

Installation

pnpm install t-state-form

Basic usage

Using the useForm hook, you can create a strong typed form.

import { useForm } from 't-state-form'

const LoginComponent = () => {
  const { useFormState, handleChange, forceValidation } = useForm({
    initialConfig: {
      email: {
        initialValue: '', // types will be inferred! :D
        required: true,
      },
      password: {
        initialValue: null as string | null, // use type casting to have more control over the types
        required: true,
      },
    },
    // add custom validation for each field
    fieldIsValid: {
      email: ({ value }) => (value.includes('@') ? true : 'Invalid email'),
      password: [
        ({ value }) =>
          value.length >= 6 ? true : 'Password must be at least 6 characters',
        ({ value }) =>
          value.length <= 20 ? true : 'Password must be at most 20 characters',
      ],
    },
  })

  const { formFields, formIsValid } = useFormState()

  function login() {
    if (!formIsValid) {
      forceValidation() // force showing validation errors
      return
    }

    // perform login
  }

  return (
    <div>
      <input
        type="text"
        value={formFields.email.value}
        onChange={(e) => handleChange('email', e.target.value)}
      />
      {formFields.password.errors && (
        <InputErrors>{formFields.email.errors}</InputErrors>
      )}

      <input
        type="number"
        value={formFields.password.value}
        onChange={(e) => handleChange('password', e.target.value)}
      />
      {formFields.password.errors && (
        <InputErrors>{formFields.password.errors}</InputErrors>
      )}

      <button type="button" onClick={() => login()} disabled={!formIsValid}>
        Login
      </button>
    </div>
  )
}
0.28.1

8 months ago

0.28.0

8 months ago

0.27.1

10 months ago

0.27.0

10 months ago

0.26.1

10 months ago

0.26.0

10 months ago

0.25.1

1 year ago

0.25.0

1 year ago

0.24.1

1 year ago

0.24.0

1 year ago

0.23.0

1 year ago

0.21.0

1 year ago

0.22.0

1 year ago

0.20.1

1 year ago

0.20.0

1 year ago

0.19.0

1 year ago

0.18.0

1 year ago

0.16.0

2 years ago

0.17.0

2 years ago

0.15.0

2 years ago

0.14.0

2 years ago

0.13.1

2 years ago

0.13.0

2 years ago

0.12.2

2 years ago

0.12.1

2 years ago

0.12.0

2 years ago

0.11.0

2 years ago

0.10.0

2 years ago

0.9.0

2 years ago

0.8.2

2 years ago

0.8.1

2 years ago

0.8.0

2 years ago

0.7.3

2 years ago

0.7.2

2 years ago

0.7.1

2 years ago

0.7.0

2 years ago

0.6.0

2 years ago

0.5.0

2 years ago

0.4.0

2 years ago

0.3.0

2 years ago

0.2.0

2 years ago

0.1.0

2 years ago