5.2.0 • Published 2 years ago

react-hooks-form-validator v5.2.0

Weekly downloads
31
License
MIT
Repository
github
Last release
2 years ago

Small. 9 KB (minified and gzipped). Size Limit controls the size.

Table of Contents

The problem

You want to write simple and maintainable form validations. As part of this goal, you want your validations to be simple yet accomadate your specifc needs. Be it in React Web or React Native. You should be able to add validations to more complicated components like Multi-Select, Date Time Picker. This also means it should easy to add validations with any design library you use,like MATERIAL-UI, Ant-D, React Bootstrap etc. or even if you don't use one. You should be able to validate form from your server or any async validations for that matter.

This solution

The React Use Form is a very lightweight solution for validating forms. It provides react hooks to configure your form, in a way that encourages simpler way to validate form. It doesn't assume anything about your design.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save react-hooks-form-validator

yarn add react-hooks-form-validator

This library has peerDependencies listings for react and react-dom.

NOTE: The minimum supported version of react is ^16.9.0.

Examples

Basic Example

import React from 'react';
import useForm from 'react-hooks-form-validator';
import { FormItem, Input, Button } from 'antd';

const formConfig = {
  username: {
    required: true,
    min: 6,
  },
  password: {
    min: 6,
    max: 20,
    required: true,
  },
};

function FormComponent() {
  const [fields, formData] = useForm(formConfig);
  async function handleLogin() {
    await login({
      username: fields.username.value,
      password: fields.password.value,
    });
  }

  return (
    <form>
      <FormItem errorMsg={fields.username.errorMsg} required>
        <Input
          id="username"
          size="large"
          placeholder="Enter your Email"
          onTextChange={fields.username.setValue}
          value={fields.username.value}
          hasFeedback
        />
      </FormItem>
      <FormItem errorMsg={fields.password.errorMsg} required>
        <Input
          type="password"
          id="password"
          size="large"
          placeholder="Enter Your Password"
          onTextChange={fields.password.setValue}
          value={fields.password.value}
        />
      </FormItem>
      <Button
        disabled={!formData.isValid}
        onClick={handleLogin}
        size="large"
        block
      >
        Login
      </Button>
    </form>
  );
}

export default FormComponent;

Complex Example

import React from 'react';
import useForm from 'react-hooks-form-validator';
import { FormItem, Input, Button } from 'antd';

const formConfig = {
  username: {
    required: true,
    min: 6,
    patterns: [
      {
        regex: new RegExp(/[a-zA-Z0-9]+/),
        errorMsg: 'Please enter a only alpha numeric username',
      },
    ],
  },
  password: {
    min: 6,
    max: 20,
    required: true,
  },
  confirmPassword: {
    validate: (fieldValue, formValue) => {
      const isPasswordSame = formValue.password === fieldValue;
      return [isPasswordSame, 'Password and confirm password should be same'];
    },
  },
};

function FormComponent() {
  const [fields, formData] = useForm(formConfig);
  async function handleLogin() {
    await login({
      username: fields.username.value,
      password: fields.password.value,
    });
  }

  return (
    <form>
      <FormItem errorMsg={fields.username.errorMsg} required>
        <Input
          id="username"
          size="large"
          placeholder="Enter your Email"
          onTextChange={fields.username.setValue}
          value={fields.username.value}
          hasFeedback
        />
      </FormItem>
      <FormItem errorMsg={fields.password.errorMsg} required>
        <Input
          type="password"
          id="password"
          size="large"
          placeholder="Enter Your Password"
          onTextChange={fields.password.setValue}
          value={fields.password.value}
        />
      </FormItem>
      <FormItem errorMsg={fields.confirmPassword.errorMsg} required>
        <Input
          type="password"
          id="confirmPassword"
          size="large"
          placeholder="Confirm Your Password"
          onTextChange={fields.confirmPassword.setValue}
          value={fields.confirmPassword.value}
        />
      </FormItem>
      <Button
        disabled={!formData.isValid}
        onClick={handleLogin}
        size="large"
        block
      >
        Sign-Up
      </Button>
    </form>
  );
}

export default FormComponent;

More Examples

You'll find runnable examples in the react-hooks-form-validator-examples codesandbox.

API Reference

Basic usage is like

const [fieldObject,formObject] = useForm(formConfig);

formConfig is object with key as fieldName and value as fieldConfig

Example for config

{
    field1: config1,
    field2: config2,
    field3: config3,
}

Field Config

keyWhat it does?TypeExample
defaultValueDefault value of the fieldany'', []
requiredTo set the field as requiredBoolean or { errorMsg : String }true or {errorMsg: 'This is required field' }
minTo set minimun length of fieldNumber or { errorMsg : String, length: Number}5 or {errorMsg: 'minimum of 5 character', length: 5}
maxTo set maximum length of fieldNumber or { errorMsg : String, length: Number}5 or {errorMsg: 'maximim of 5 character', length: 5}
patternsTo validate against array of patternsArray of {regex : RegExp, errorMsg: String}[{regex: new RegExp(/[a-zA-Z0-9]+/), errorMsg: "Please enter a only alpha numeric username" }]
validateFunction To validate(fieldValue,formState) => [isValid, errorMessage][(fieldValue, formState) => [!!formState.country.id, 'Country id is mandatory']]

Field Object

keyWhat it does?Type
valueCurrent value of the fieldany
errorMsgError message of the fieldString
isValidValidity of the fieldBoolean
setValueFunction to set value and validate field(value) => {}
updateConfigFunction to partially update a fields config(curentFieldConfig) => partialFieldConfig
validateFunction to validate the field() => {}
setValueOnlyFunction only set value without validating(value) => {}

Form Object

keyWhat it does?TypeExample
isValidValidity of the formBoolean
validateFunction to validate the form() => {}
addFieldConfigDynamically add a fieldfn(fieldName, fieldConfig) or fn(fieldName, (formState)) => fieldConfigformObject.addFieldConfig('useraname', { required: true }) or formObject.addFieldConfig('useraname', (formState) => { required: !formState.email })
removeFieldConfigDynamically remove a fieldfn(fieldName)formObject.removeFieldConfig('useraname')
resetResets the form config before adding or removing fields() => {}
configCurrent form config{}

LICENSE

MIT

5.2.0

2 years ago

5.0.2

2 years ago

5.1.0

2 years ago

5.0.1

2 years ago

4.0.0

2 years ago

3.1.0

3 years ago

3.0.4

3 years ago

3.0.2

3 years ago

3.0.1

3 years ago

3.0.0

4 years ago

1.1.0

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago