Giter Site home page Giter Site logo

balavishnuvj / react-hooks-form-validator Goto Github PK

View Code? Open in Web Editor NEW
3.0 2.0 1.0 2.11 MB

One react hook for all your form validations

License: MIT License

JavaScript 100.00%
react reactjs react-native use-form hooks react-hooks react-hook form-validation form-validator form-validation-react

react-hooks-form-validator's Introduction

React Hooks Form Validator

martial arts uniform

Simple, extensible and config based form validation.

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

key What it does? Type Example
defaultValue Default value of the field any '', []
required To set the field as required Boolean or { errorMsg : String } true or {errorMsg: 'This is required field' }
min To set minimun length of field Number or { errorMsg : String, length: Number} 5 or {errorMsg: 'minimum of 5 character', length: 5}
max To set maximum length of field Number or { errorMsg : String, length: Number} 5 or {errorMsg: 'maximim of 5 character', length: 5}
patterns To validate against array of patterns Array of {regex : RegExp, errorMsg: String} [{regex: new RegExp(/[a-zA-Z0-9]+/), errorMsg: "Please enter a only alpha numeric username" }]
validate Function To validate (fieldValue,formState) => [isValid, errorMessage] [(fieldValue, formState) => [!!formState.country.id, 'Country id is mandatory']]

Field Object

key What it does? Type
value Current value of the field any
errorMsg Error message of the field String
isValid Validity of the field Boolean
setValue Function to set value and validate field (value) => {}
updateConfig Function to partially update a fields config (curentFieldConfig) => partialFieldConfig
validate Function to validate the field () => {}
setValueOnly Function only set value without validating (value) => {}

Form Object

key What it does? Type Example
isValid Validity of the form Boolean
validate Function to validate the form () => {}
addFieldConfig Dynamically add a field fn(fieldName, fieldConfig) or fn(fieldName, (formState)) => fieldConfig formObject.addFieldConfig('useraname', { required: true }) or formObject.addFieldConfig('useraname', (formState) => { required: !formState.email })
removeFieldConfig Dynamically remove a field fn(fieldName) formObject.removeFieldConfig('useraname')
reset Resets the form config before adding or removing fields () => {}
config Current form config {}

LICENSE

MIT

react-hooks-form-validator's People

Contributors

balavishnuvj avatar dependabot[bot] avatar khedau avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

khedau

react-hooks-form-validator's Issues

Support Typescript

@types/react-hooks-form-validator
I hopefully typescript will be supported

Custom Error Message

i wanted to add a custom error message for my required form field. but readme did not show anyway of adding it.
but then i checked code and field validator was taking it. pls update the readme with all fields properties
thanks :)

required: [
    { type: 'boolean', optional: true },
    {
      type: 'object',
      optional: true,
      props: {
        errorMsg: { type: 'string' },
      },
    },
  ]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.