revalidation

Higher Order Component for Validating Forms in React

View the Project on GitHub

API

Revalidation(Component)

Creates an enhanced React Component containing validation and state keeping capabilities.

Arguments

  1. Component (React Component): The React Component that will be enhanced with validation and state keeping functionality.

Returns

<HigherOrderComponentForm />

Higher Order React Component: The provided component will be enhanced with a revalidation prop.

Props

Example

import React from 'react'
import Revalidation, { isValid } from 'revalidation'
import { head } from 'ramda'

import helpers from './helpers'

const {
  isNotEmpty,
  isLengthGreaterThan,
  hasCapitalLetter,
} = helpers

const displayErrors = (errorMsgs) =>
  isValid(errorMsgs) ? null : <div className='error'>{head(errorMsgs)}</div>

const getValue = e => e.target.value

const Form = ({ revalidation : {form, validate, valid, errors = {}, onSubmit}, onSubmitCb }) =>
  (
    <div className='form'>
      <div className='formGroup'>
        <label>Name</label>
        <input
          type='text'
          value={form.name}
          onChange={e => validate('name', getValue(e))}
        />
        { errors.name }
      </div>
      <div className='formGroup'>
        <label>Random</label>
        <input
          type='text'
          value={form.random}
          onChange={e => (validate('random', getValue(e))}
        />
        { displayErrors(errors.random) }
      </div>
      <button onClick={() => onSubmit(onSubmitCb)}>Submit</button>
    </div>
  )

const EnhancedForm = Revalidation(Form)

// ...usage

const initialState = {name: '', random: ''}

const validationRules = {
  name: [
    [isNotEmpty, 'Name should not be  empty.']
  ],
  random: [
    [isLengthGreaterThan(7), 'Minimum Random length of 8 is required.'],
    [hasCapitalLetter, 'Random should contain at least one uppercase letter.'],
  ]
}


<EnhancedForm
    initialState={initialState}
    rules={validationRules}
    validateSingle
    validateOnChange
/>


revalidation

An additional prop revalidation is provided to the enhanced component.

The following properties are provided by revalidation.

Additionally revalidation offers a number of helper functions to quickly update any values or validations.

===

Helpers

isValid

Use isValid to check if errors exist for an input.


<input
  type='text'
  className={isValid(errors.name) ? '' : 'error'}
  value={form.name}
  onChange={compose(onChange('name'), getValue)}
/>