@q-dev/form-hooks
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-rc.12 • Public • Published

Q Form Hooks

A set of form hooks with validation for Q Blockchain frontend projects.

npm npm min zipped size license pipeline status

Installation

To install the library, run the following command:

yarn add @q-dev/form-hooks

or

npm install @q-dev/form-hooks

Requirements

Usage

Form with validation

import { useForm, required } from '@q-dev/form-hooks';

const form = useForm({
  initialValues: {
    name: '',
    email: '',
    password: '',
  },
  validators: {
    name: [],
    email: [required],
    password: [required],
  },
  onSubmit: (values) => {
    console.log(values);
  },
});

Custom validation

import { useForm, required } from '@q-dev/form-hooks';

const form = useForm({
  initialValues: {
    name: '',
    email: '',
    password: '',
  },
  validators: {
    name: [],
    email: [required],
    password: [
      required,
      val => ({
        isValid: !val || PASSWORD_REGEX.test(String(val)),
        message: 'Invalid password',
      })
    ],
  },
  onSubmit: (values) => {
    console.log(values);
  },
});

Translations

Translations can be provided with type property from validator object. Types for each validator can be found here.

import { useForm, required } from '@q-dev/form-hooks';

const form = useForm({
  initialValues: { name: '' },
  validators: { name: [] },
  onSubmit: (values) => {
    console.log(values);
  }
});

const { t } = useTranslation();
const translateError = (type: string) => {
  switch (type) {
    case 'required':
      return t('validation.required');
    default:
      return error;
  }
};

JSX

import { useForm, required } from '@q-dev/form-hooks';

const form = useForm({
  initialValues: { name: '' },
  validators: { name: [] },
  onSubmit: (values) => {
    console.log(values);
  }
});

return (
  <form onSubmit={form.submit}>
    <input
      type="text"
      name="name"
      value={form.values.name}
      onChange={e => form.fields.name.onChange(e.target.value)}
    />
    {form.errors.name && <span>{form.errors.name}</span>}
    {/* or with Q UI Kit input */}
    {/* https://gitlab.com/q-dev/q-web-kit/-/blob/main/packages/ui-kit/src/components/Input/Input.tsx */}
    <Input {...form.fields.name} />
    <button type="submit">Submit</button>
  </form>
);

Contribution

We welcome contributions to the library. If you would like to submit a pull request, please make sure to follow our code style.

Code of Conduct

This project and everyone participating in it is governed by the Q Form Hooks Code of Conduct. By participating, you are expected to uphold this code.

Resources

License

LGPL-3.0

Readme

Keywords

none

Package Sidebar

Install

npm i @q-dev/form-hooks

Weekly Downloads

72

Version

1.0.0-rc.12

License

LGPL-3.0

Unpacked Size

306 kB

Total Files

57

Last publish

Collaborators

  • aostrun
  • tynuk
  • misterzett
  • tbltzk