1.5.0 โ€ข Published 1 year ago

reactjs-use-form v1.5.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

useForm(๐Ÿ“‹, โš™๏ธ) โ‡’ Reactive Form โš›๏ธ

build and tests code style: prettier GitHub code size in bytes npm minified bundle size npm gzipped bundle size typescript

Reactive form management and input field validation hook

Create a form model, flag input fields as required or add a value validation function with custom error messages. useForm will validate the inputs as the user types, when there are no errors the form gets enabled for submission. On form submission, it executes a callback function the user provides.

Requirements:
  • ๐Ÿ“‹ Form model with optional validation function.
  • โš™๏ธ Function to run after form validation and submission.
  • โš›๏ธ React functional component with a form.

Install

npm install reactjs-use-form

Usage

Steps:
  1. create a form model:
import { FormModelType } from 'reactjs-use-form';

export const formModel: FormModelType = {
  currentPassphrase: {
    value: '',
    required: true,
  },
  newPassphrase: {
    value: '',
    required: true,
    validator: (newPassphrase, values) => {
      if (newPassphrase === values?.currentPassphrase) {
        return 'New password must be different from current password';
      } else if (newPassphrase.length <= 5) {
        return 'Password must be at least 6 characters long';
      } else if (newPassphrase !== values?.verifyPassphrase) {
        return 'Passwords do not match';
      } else return '';
    },
  },
  verifyPassphrase: {
    value: '',
    required: true,
    validator: (verifyPassphrase, values) => {
      return verifyPassphrase !== values?.newPassphrase ? 'Passwords do not match' : '';
    },
  },
};
  1. prepare a submit callback function, for example: function handleSubmit() {...}.

  2. use the form model with the callback function in useForm hook in a functional react component:

import React from 'react';
import { useForm, ValuesType } from 'reactjs-use-form';
import { formModel } from './formModel';

const ChangePassphraseComponent = () => {
  const {
    values,
    errors,
    handleOnChange,
    handleOnSubmit,
    isDisabled,
    isSubmitted,
    isDirty
  } = useForm(formModel, handleSubmit);

  const { currentPassphrase, newPassphrase, verifyPassphrase }: ValuesType = values;

  function handleSubmit() {
    if (isDirty) formSubmitCallback();
  }

  return (
    <form onSubmit={handleOnSubmit}>
      <div>
        <label>Current Passphrase</label>
        <input
          type="password"
          name="currentPassphrase"
          value={currentPassphrase}
          onChange={handleOnChange}
        />
        <span>{errors.currentPassphrase.message}</span>
      </div>
      <div>
        <label>New Passphrase</label>
        <input
          type="password"
          name="newPassphrase"
          value={newPassphrase}
          onChange={handleOnChange}
        />
        <span>{errors.newPassphrase.message}</span>
      </div>
      <div>
        <label>Verify Passphrase</label>
        <input
          type="password"
          name="verifyPassphrase"
          value={verifyPassphrase}
          onChange={handleOnChange}
        />
        <span>{errors.verifyPassphrase.message}</span>
      </div>
      <span>{isSubmitted ? 'Passphrase has been changed!' : null}</span>
      <button type="submit" disabled={isDisabled}>
        <span>Submit</span>
      </button>
    </form>
  );
};
import React from 'react';
import { Button, FormControl, FormGroup, FormHelperText, FormLabel, TextField } from '@material-ui/core';
import { useForm, ValuesType } from 'reactjs-use-form';
import { formModel } from './formModel';

const ChangePassphraseComponent = () => {
  const {
    values,
    errors,
    handleOnChange,
    handleOnSubmit,
    isDisabled,
    isSubmitted,
    isDirty
  } = useForm(formModel, handleSubmit);

  const { currentPassphrase, newPassphrase, verifyPassphrase }: ValuesType = values;

  function handleSubmit() {
    if (isDirty) formSubmitCallback();
  }

  return (
    <form onSubmit={handleOnSubmit}>
      <FormGroup>
        <FormControl>
          <TextField
            required={true}
            label='Current Passphrase'
            type='password'
            name='currentPassphrase'
            error={errors.currentPassphrase.hasError}
            value={currentPassphrase}
            onChange={handleOnChange} />
          <FormHelperText error={errors.currentPassphrase.hasError}>
            {errors.currentPassphrase.message}
          </FormHelperText>
        </FormControl>
      </FormGroup>
      <FormGroup>
        <FormControl>
          <TextField
            required={true}
            label='New Passphrase'
            type='password'
            name='newPassphrase'
            error={errors.newPassphrase.hasError}
            value={newPassphrase}
            onChange={handleOnChange} />
          <FormHelperText error={errors.newPassphrase.hasError}>
            {errors.newPassphrase.message}
          </FormHelperText>
        </FormControl>
      </FormGroup>
      <FormGroup>
        <FormControl>
          <TextField
            required={true}
            label='Verify Passphrase'
            type='password'
            name='verifyPassphrase'
            error={errors.verifyPassphrase.hasError}
            value={verifyPassphrase}
            onChange={handleOnChange} />
          <FormHelperText error={errors.verifyPassphrase.hasError}>
            {errors.verifyPassphrase.message}
          </FormHelperText>
        </FormControl>
      </FormGroup>
      {isSubmitted ? <Alert variant='standard' severity='success' action='Passphrase has been changed!' /> : null}
      <Button type='submit' disabled={isDisabled}>
        Submit
      </Button>
    </form>
  );
};

Options

useForm takes two params: formModel and formSubmitCallback and returns the rest.

const {
  values,
  errors,
  handleOnChange,
  handleOnSubmit,
  isDisabled,
  isSubmitted,
  isDirty
} = useForm(formModel, formSubmitCallback);
ParamTypeDescription
valuesValuesTypereturns form values state object
errorsErrorsTypereturns form errors state object
handleOnChangeHandleOnChangeTypebinds to a HTMLInputElement: change event
handleOnSubmitHandleOnSubmitTypebinds to a HTMLFormElement: submit event
isDisabledbooleanreturns true / false when the form is valid / invalid
isSubmittedbooleanreturns true when the form was submitted without errors
isDirtybooleanreturns true when the form recieves data
formModelFormModelTypeinitial form model with optional validation function
formSubmitCallback() => voidfunction to run after form validation and submission

Type definitions: docs/definitions.md

License

GitHub

1.5.0

1 year ago

1.5.0-beta.0

1 year ago

1.4.6

2 years ago

1.4.5

2 years ago

1.4.4

2 years ago

1.4.2

2 years ago

1.4.7

1 year ago

1.4.1

2 years ago

1.4.0

2 years ago

1.3.9

2 years ago

1.3.8

2 years ago

1.3.7

3 years ago

1.3.6

3 years ago

1.3.5

3 years ago

1.3.4

3 years ago

1.3.3

3 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.9

3 years ago

1.2.8

3 years ago

1.2.7

3 years ago

1.2.6

3 years ago

1.2.5

3 years ago

1.2.0

3 years ago

1.1.9

3 years ago

1.2.4

3 years ago

1.2.3

3 years ago

1.2.2

3 years ago

1.2.1

3 years ago

1.1.7

3 years ago

1.1.6

3 years ago

1.1.5

3 years ago

1.1.4

3 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago