1.0.9 • Published 4 years ago

form-control-react v1.0.9

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

form-control-react

Control and Validate forms in React

NPM JavaScript Style Guide

Install

npm install --save form-control-react

Example

Demo

Usage

Create config object (can be a separate file to increase readability)

// App.config.ts

export const config = {
  firstName: {
    required: true,
    validators: [
      value => ({
        valid: value.length > 2,
        errorMsg: "Must be at least 3 characters long"
      })
    ]
  }
};

Implement the hook directly onto native/custom HTML Elements/React Components

//App.tsx

import React from "react";
import { useForm } from "form-control-react";
import { config } from "./App.config";

export default const App = () => {
  const { getFields,handleChange,valid } = useForm(config);

  const { firstName } = getFields();
  return (
    <>
      <form>
        <div>
          <label htmlFor="firstName">First Name</label>
          <input
            onChange={handleChange}
            type="text"
            name="firstName"
            {...firstName}
          />
          <span>{firstName.errorMsg}</span>
        </div>
      </form>
      <button disabled={!valid}>Submit</button>
    </>
  );
};

export default App;

API

// CONFIG OBJECT
{
  fieldName: {
    disabled?: boolean, // should the field be disabled
    required?: boolean, // if the field should be counted when validating the form
    value?: string | number | [] | {} | boolean, // if you want to initially set values to a form
    valid?: boolean, // if you want to intitially manually set validity
    validators?: [ // an array of validator functions
      (value) => ({
        valid: value > 0, // validation expression or regex match
        errorMsg: 'Must be higher than 0' // message in case of invalidity
    })],
  }
}

// useForm API
{
  getValues, // collects all values from fields
  getFields, // returns all fields along with their validity states
  handleBlur, // on required fields it will delete value if invalid, otherwise updates the value
  handleChange, // updates the state and validates the form on keystroke
  reset, // resets the form to initial values
  setFields, // sets the fields dynamically (if data comes from an API)
  valid, // global form validity flag
  validate, // run global validation and return validity flag
}

License

MIT © NicolasBG87


This hook is created using create-react-hook.

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago