form-validation-hooks

0.0.1Β β€’Β PublicΒ β€’Β Published



🎣
form-validation-hooks


React hooks to help validate forms

npm MIT License Travis Codecov

Β 

Validate individual inputs.

import React from 'react';

// πŸ‘‡ Import form-validation-hooks.
import { useValidations, useTouched } from 'form-validation-hooks';

const Input = ({ name, value, type, form, validations, handleChange }) => {
  // πŸ‘‡ Validate inputs.
  const errors = useValidations({ name, value, form, validations });

  // πŸ‘‡ Get touched state.
  const touched = useTouched(value);

  // πŸ‘‡Conditionally render errors based on touched state.
  return (
    <>
      <input name={name} value={value} onChange={handleChange} type={type} />
      <p>
        <small style={{ color: 'red' }}>{touched && errors.join(' ')}</small>
      </p>
    </>
  )
}

Validate the entire state of a form.

import React, { useState } from 'react';
import Input from './Input';

// πŸ‘‡ Import form-validation-hooks.
import { useForm } from 'form-validation-hooks';

// πŸ‘‡ Import custom validations.
import validations from './validations';

const SignupForm = () => {
  const [user, setUser] = useState({
    email: '',
    password: '',
    confirmPassword: '',
    test: '',
  });

  // πŸ‘‡ Validate the entire form.
  const form = useForm({ validations, form: user })

  const handleChange = (event) => {
    const { target, target: { name } } = event;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    setUser({ ...user, [name]: value });
  }

  // πŸ‘‡ Disable submit button if form is invalid.
  return (
    <>
      <label>Email:</label>
      <Input
        name="email"
        type="text"
        value={user.email}
        validations={validations}
        form={user}
        handleChange={handleChange}
      />

      <label>Password:</label>
      <Input
        name="password"
        type="password"
        value={user.password}
        validations={validations}
        form={user}
        handleChange={handleChange}
      />

      <label>Confirm Password:</label>
      <Input
        name="confirmPassword"
        type="password"
        value={user.confirmPassword}
        validations={validations}
        form={user}
        handleChange={handleChange}
      />

      <button disabled={!form.isValid}>Signup</button>
    </>
  );
};

Write your own validations.

const validEmail = (value) => {
  if (/@/.test(value)) return;
  return 'Invalid email address.';
};

const length = ({ min = 2, max = 10 }) => (value) => {
  if (value.length < min) return `Must be at least ${min} characters.`;
  if (value.length > max) return `Must be less than ${max} characters.`;
  return;
};

const matchingValues = ({ name, label = name } = {}) => (value, form) => {
  if (value === form[name]) return;
  return `Does not match ${label}.`;
};

const validations = {
  email: [validEmail],
  password: [length({ min: 6, max: 24 })],
  confirmPassword: [matchingValues({ name: 'password' })],
};

Β 

Introduction

npm install form-validation-hooks

form-hook-validations is a set of hooks that can validate the entire state of a form, or just an input. You bring in your own validations.

Features

  • Validate individual input fields.
  • Validate the entire form.
  • Validations based on sibling input fields.
  • Custom validations.
  • Keep validations outside of your component.
  • Keep track of touched/dirty state.

Β 


API Reference

useValidations({ name, value, validations, form })

Arguments

  1. options (object):
    1. name (string): The key/name of the input being validated.
    2. value (any): The value of the input.
    3. validations (object): An object that specifies validations for each input.
    4. form (object): Optional, the form object which holds all of the form data.

Returns

(array): An array containing all of the validations error for the input, the array will be empty if there are no validation errors.

['Invalid email address.']

Example

const errors = useValidations({ name, value, form, validations });

useForm({ validations, form })

Arguments

  1. options (object):
    1. validations (object): An object that specifies validations for each input.
    2. form (object): Optional, the form object which holds all of the form data.

Returns

(object): An objecting containg all form errors and valid state.

{
  isValid: true, // true or false
  errors: {
    // There will be a key for inputs with specified validations.
    // An array containing all of the validations error for the input, the array will be empty if there are no validation errors.
    email: [],
    confirmPassword: []
  }
}

Example

const form = useForm({ validations, form: user })

useTouched(value)

Arguments

  1. value (any): The initial value of the input.

Returns

(boolean): Defaults to false, turns true after the value changes and never goes back to false.

Example

import React from 'react';
import { useValidations, useTouched } from 'form-validation-hooks';

const Input = ({ name, value, type, form, validations, handleChange }) => {
  const errors = useValidations({ name, value, form, validations });

  // πŸ‘‡ Get touched state.
  const touched = useTouched(value);

  // πŸ‘‡ Conditionally render errors.
  return (
    <>
      <input name={name} value={value} onChange={handleChange} type={type} />
      <p>
        <small style={{ color: 'red' }}>{touched && errors.join(' ')}</small>
      </p>
    </>
  )
}
export default Input;

useDirty(value)

Arguments

  1. value (any): The initial value of the input.

Returns

(boolean): Defaults to false, turns true after the value changes and goes back to true if the value returns to its initial value.

Example

import React from 'react';
import { useValidations, useDirty } from 'form-validation-hooks';

const Input = ({ name, value, type, form, validations, handleChange }) => {
  const errors = useValidations({ name, value, form, validations });

  // πŸ‘‡ Get dirty state.
  const dirty = useDirty(value);

  // πŸ‘‡ Conditionally render errors.
  return (
    <>
      <input name={name} value={value} onChange={handleChange} type={type} />
      <p>
        <small style={{ color: 'red' }}>{dirty && errors.join(' ')}</small>
      </p>
    </>
  )
}
export default Input;

useInput({ name, value, validations, form })

Arguments

  1. options (object):
    1. name (string): The key/name of the input being validated.
    2. value (any): The value of the input.
    3. validations (object): An object that specifies validations for each input.
    4. form (object): Optional, the form object which holds all of the form data.

Returns

(object): An object containing the result of useTouched, useDirty, and useValidations.

{
  touched: false,
  dirty: false,
  errors: {
    email: [],
  }
}

Example

import React from 'react';
import { useInput } from 'form-validation-hooks';

const Input = ({ name, value, type, form, validations, handleChange }) => {
  // πŸ‘‡ Get input state.
  const input = useInput({ name, value, form, validations });

  // πŸ‘‡ Conditionally render errors.
  return (
    <>
      <input name={name} value={value} onChange={handleChange} type={type} />
      <p>
        <small style={{ color: 'red' }}>{input.dirty && input.errors.join(' ')}</small>
      </p>
    </>
  )
}
export default Input;

Β 


Examples

Sign up form

This GitHub repository shows off how to utilise form-validation-hooks and covers every feature.

https://github.com/codyeatworld/signup-form-validation-hooks

Readme

Keywords

none

Package Sidebar

Install

npm i form-validation-hooks

Weekly Downloads

0

Version

0.0.1

License

MIT

Unpacked Size

222 kB

Total Files

17

Last publish

Collaborators

  • coverhound_admin