• Stars
    star
    118
  • Rank 299,923 (Top 6 %)
  • Language
    TypeScript
  • Created over 7 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React Forms with Zod Validation

Controlled Forms

react-controlled-form aims to simplify form management in React.
It ships functional APIs to create your very own form fields and is built with flexibility and customization in mind.

It allows you to bring your own components.
You do not have to struggle with predefined input components ever again!
It only uses React Hooks under-the-hood and is thus super fast.

npm downloads npm version

Installation

yarn add react-controlled-form

Controlled Forms requires react>=16.3.0 to be installed in your project.

Benefits

  • simple functional API
  • Controlled state using useState
  • full flexibility
  • custom form fields
  • reactive forms

The Gist

import { useField, useForm } from 'react-controlled-form'

function Input({ isValid, errorMessage, ...props }) {
  return (
    <div>
      <input style={{ borderColor: isValid ? 'black' : 'red' }} {...props} />
      {errorMessage && <div>{errorMessage}</div>}
    </div>
  )
}

const nameValidation = {
  'Please enter at least 2 characters.': (value) => value.length >= 2,
  'Only use alphabetic letters.': /^[a-z]*$/gi,
}

function Form() {
  const firstname = useField({
    name: 'firstname',
    validation: nameValidation,
  })

  const lastname = useField({
    name: 'firstname',
    validation: nameValidation,
  })

  const { submit, reset } = useForm(firstname, lastname)

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()

        submit((isValid, data) => {
          if (isValid) {
            console.log('Submitted: ', data)
            reset()
          }
        })
      }}>
      <Input {...firstname.props} />
      <Input {...lastname.props} />
      <input type="submit" />
    </form>
  )
}

API

useField(options)

This hook uses React.useState under-the-hood and controls the state changes and validation for each field. The internal representation of a field contains the following properties:

  • value
  • isValid
  • isTouched
  • isDisabled
  • isRequired
  • isLoading
  • errorMessage

Options

Option ย Description
value The initial value.
touched ย The initial isTouched value.ย 
loading ย The initial isLoading value.ย 
disabled ย The initial isDisabled value.ย 
required ย The initial isRequired value.ย 
validation ย An map of errorMessage-validator where validator can either be a function of value or a RegExp.
showValidationOn ย When the field is "touched" and isValid / errorMessage are passed to the props.
Can be change or blur.

Returns

(Object) An object containing the following properties:

const shape = {
  // Those can be passed to your custom input implementation
  props,
  // A function used to update manually the field (use with caution)
  // It either takes properties from the internal field listed above
  // or a function of the current field that returns the new field
  update,
  initial,
  name,
  value,
  isValid,
  isTouched,
  isDisabled,
  isRequired,
  errorMessage,
}

useForm(...fields)

This hook takes a list of fields, where a field is the output of the useField hook.

Returns

(Object) An object containing the following properties:

const shape = {
  // Takes a function of (isValid, data) where isValid is the global validation state and data is a map of name-value
  // Calling submit will automatically touch all fields to reveal the error messages (if not already shown)
  submit,
  // Resets the form to its initial state
  reset,
  // Touches each field to reveal their validation state & error messages
  touchFields,
}

useFormDebugger(...fields)

This hook is only meant for debugging reasons. It takes the same fields as useForm, but returns all the field data on every render.

Returns

(Object) An object containing the following properties:

const shape = {
  // A map of name-value pairs
  data,
  // A map of name-field pairs, where field represents the full internal representation of each field
  fields,
  // The global validation state which is accumulated by checking each field's isValid
  isValid,
}

createUseField(resolveProps)

This factory function can be used to create your very own version of useField which can be useful if you want to implement different behaviour or return different props.

It takes a function that receives an object with the following shape:

const params = {
  // All values from the internal field representation
  field,
  // A function used to validate the value according to the passed validation object
  validate,
  // The update function which is also returned by useField and described above
  update,
  // Any additionally passed options that are not directly part of the field representation e.g. showValidationOn
  options,
}

Usage

import { createUseField } from 'react-controlled-form'

function resolveProps({ field, update, validate, options }) {
  const { name, value, isValid, isDisabled, isRequired } = field

  return {
    value,
    name,
    required: isRequired,
    disabled: isDisabled,
    onChange: (e) =>
      update({
        value: e.target.value,
        isValid: validate(e.target.value),
      }),
    style: {
      borderColor: isValid ? 'black' : options.validationColor,
    },
  }
}

const useField = createUseField(resolveProps)

// Usage
const firstname = useField({
  name: 'firstname',
  validationColor: 'pink',
  validation: {
    'Enter at least 2 characters.': (value) => value.length >= 2,
  },
})

// this will render an input with pink borders for invalid values
const Firstname = () => <input {...firstname.props} />

Examples

License

react-controlled-form is licensed under the MIT License.
Created with โ™ฅ by @robinweser and all the great contributors.

More Repositories

1

fela

State-Driven Styling in JavaScript
JavaScript
2,273
star
2

react-look

Advanced & Dynamic Component Styling for React and React Native. Ships with powerful Plugins, Mixins and Developer Tools. (Deprecated: use Fela)
JavaScript
583
star
3

inline-style-prefixer

Autoprefixer for JavaScript style objects
JavaScript
393
star
4

react-layout-components

Layout Components for React based on Flexbox
JavaScript
337
star
5

react-css-component

Injecting CSS via React Components
JavaScript
94
star
6

alveron

Tiny (0.8kb) Elm-inspired state management for React
JavaScript
74
star
7

css-in-js-utils

Useful utility functions for CSS in JS solutions
TypeScript
74
star
8

bredon

A modern CSS value compiler in JavaScript
JavaScript
40
star
9

elodin

The Elodin Styling Language
JavaScript
30
star
10

fast-loops

Tiny (0.6kb), performant & immutable iteration utilities for arrays and objects
JavaScript
25
star
11

kilvin

Primitive React Layout Components using Fela
JavaScript
22
star
12

alveron-old

Opinionated Elm-inspired Redux Component Architecture for React
JavaScript
17
star
13

inline-style-prefix-all

Static Autoprefixer for inline styles
JavaScript
16
star
14

elodin-old

Quality and Optimisation tools for CSS in JavaScript
JavaScript
16
star
15

inline-style-expand-shorthand

Expanding shorthand properties in JavaScript style objects
JavaScript
13
star
16

brandeur

Convenience tool belt for css-hooks
JavaScript
12
star
17

small-color

Tiny (0.8kb), opinionated & tree-shakable alternative to color
JavaScript
7
star
18

small-date

Tiny (0.8kb) date formatting library with built-in i18n
JavaScript
6
star
19

tehlu

Component System for React and Brandeur
JavaScript
5
star
20

Calculate.js

Calculate.js is kind of an extension to the JavaScript build-in Math-Library.
JavaScript
5
star
21

ambrose

Configurable Design System Skeleton for React
JavaScript
5
star
22

react-markdown-github-renderers

react-markdown renderers for GitHub-like appearance
JavaScript
5
star
23

pogolookup

Ads-free, Privacy-first Pokemon Go Data Lookup & Analysis Fanpage
JavaScript
5
star
24

inline-style-transformer

Transformation tools for inline styles
JavaScript
5
star
25

lorren

A PDF Framework for React based on react-pdf
JavaScript
4
star
26

radium-plugin-prefix-all

Radium plugin that adds all vendor prefixes
JavaScript
4
star
27

react-create-keyframe

Helper to create and render keyframes on-demand in React
TypeScript
3
star
28

Obscene-UI

[Sass] Obscene UI is a responsive, mobile-friendly UI-Template to build stable and beautiful app themes
CSS
3
star
29

assign-styles

ES6 Object.assign() polyfill especially for inline-styles respecting !important notation
JavaScript
3
star
30

radium-plugin-linter

[devTool] Radium plugin that enables style linting with inline-style-linter
JavaScript
2
star
31

read-transform-write

Transform files with ease
JavaScript
2
star
32

doc-badges

Useful badges for Code & API documentation
2
star
33

theme-centric-component-design

Example for theme-centric component design
JavaScript
2
star
34

tokenize-sync

Simple synchronous string tokenizer using Regex
JavaScript
1
star
35

react-onegraph

React Bindings for OneGraph's Authentication Client
JavaScript
1
star
36

unitless-css-property

Helper to check for unitless CSS property names
JavaScript
1
star
37

rofrischmann

My personal portfolio webpage
HTML
1
star
38

speaking

Speaker resources and talk slides
JavaScript
1
star
39

flow-semantic-versioning

Enforced Semantic Versioning for Flow
JavaScript
1
star