JSPM

  • Created
  • Published
  • Downloads 22605
  • Score
    100M100P100Q159045F
  • License MIT

Custom hook to account for state and validation off single state value

Package Exports

  • use-state-validate
  • use-state-validate/lib/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (use-state-validate) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

use-state-validate

Version npm

NPM

Repo: https://gitlab.com/tkil/use-state-validate

Install

npm install use-state-validate --save
  import useStateValidate from 'use-state-validate';
  // or
  const useStateValidate = require('use-state-validate');

Summary

This package contains a custom hook that blends useState and field validation. useStateValidate is focused on the validation of single state values in your form and does not try to handle all of the form logic. My motivation was to create a clean and terse pattern for dealing with state validation in react. There are MANY libraries and packages out there, but none have resonated with me just yet. So here we are... Enjoy and I hope this helps you in your next project. Please reach out to me or throw an issue on my gitlab if you have any troubles 😀

Code

import useStateValidate from "use-state-validate";

const [nameV, setName, cleanName] = useStateValidate("Tim", {
  required: true
  message: {
    required: "A name is required"
  }
});
console.log(nameV.value); // Tim
console.log(nameV.isValid); // false

Hook Signature

const [<fieldStates>, <fieldActions>] = useStateValidate(<initVal>, <rules>)

fieldStates - An object wrapping the value and relevant flags

  • value - The actual value (think the first tuple in setState)
  • name - The name configured in the rules object, handy for applying to input labels.
  • isDirty - (Default: false) - Flag for a field change
  • isRequired - (Default: false) - Flag taken from the rules object, can be useful for annotating field objects.
  • isValid - true if the value passes the rule object's validation, false if it does not
  • errors - a string array of messages corresponding to failed validation rules.

fieldActions - An object wrapping the value and relevant flags

  • setValue - Sets the value, marks the field as dirty, applies validation rules and causes a re-render (via setState)
  • setClean - Manually marks the field as clean and causes a re-render (via setState)
  • setDirty - Manually marks the field as dirty and causes a re-render (via setState)
fieldStates An object containing the raw value and validation data, use <valWrap>.value to get the value
fieldActions Set function, that behaves like useState. PLEASE PASS THE RAW VALUE HERE, not a wrapper like object!
cleanVal Function to clean the dirty flag. The dirty flag defaults to false, but is set to true if setVal is invoked
initVal The initial value to start with
rules A mostly flat object using rules outlined in this readme

Rule Examples

{
  "required": true,
  "size": { "min": 8, "max": 255 },
  "message": {
    "required": "Your field is required please",
    "size": "Use between 8 and 255 characters please"
  }
}

{
  "match": /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/,
  "message": {
    "match": "Pass my crazy regex!"
  }
}

Illustration of valueWrapped, showing the validation wrapper object

{
  "value": "value of field",
  "name": "label given to wrapper",
  "isDirty": false,
  "isRequired": true,
  "isValid": false,
  "type": "string",
  "errors": [
    "Error Message 1",
    "Error Message 2"
  ]
}

Basic Usage

import React from "react";
import useStateValidate from "use-state-validate";

const Component: React.FC = () => {
  const [nameV, setName, cleanName] = useStateValidate("Ray Finkle", {
    required: true
    match: /[a-zA-Z ]/
    message: {
      required: "You must enter a name!",
      match: "Please use only letters",
    }
  });
  return (
    <section>
      <label> Name:
        <span>{nameV.value}</span>
      </label>
      <hr />
      <input value={nameV.value} onChange={(evt) => setName(evt.target.value)}/>
      <button onClick={cleanName}>Clean it</button>
      <hr />
      <div> ⬇️ Show Me the Data! ⬇️ </div>
      <pre>{JSON.stringify(nameV, null, 2)}</pre>
    </section>
  );
};

Rules

Required

Validation requires a value, undefined, null, and "" will cause validation to fail.

{
  required: true
  message: {
    required: "You must enter a name!",
  }
}

Length

Validation requires values to match the provided type.

{
  length: { min: 3, max: 10 }
  message: {
    length: "You must enter a value between 3 and 10 characters long!",
  }
}

Enum

Validation requires value to match a provided enum.

{
  enum: ["apple", "banana", "orange"]
  message: {
    enum: "Your value must be an apple, banana or orange !",
  }
}

Match

Validation requires values to match the provided regex.

{
  match: /[A-Za-z0-9]/
  message: {
    match: "You must enter an alphanumeric value!",
  }
}

Function / Fn

Validation requires values to match the provided regex.

{
  function: (value) => {
    value === "blue"
  }
  message: {
    function: "The function wants blue!",
  }
}

or...

{
  fn: (value) => {
    value === "blue"
  }
  message: {
    fn: "The function wants blue!",
  }
}

Changelog

  • v2.5.4 - Bugfix - required, message type
  • v2.5.1 - Bugfix
  • v2.4.0 - Adds name to IStateValidateRules and validation wrapper
  • v2.3.0 - Exposes IStateValidateRules
  • v2.2.0 - Adds types to rules object
  • v2.1.0 - Adds types to validation wrapper
  • v2.0.3 - React version bugfix
  • v2.0.0 - Drops 3rd party dep and this project does its own validation
  • v1.0.6 - No breaking changes, but departs from 3rd party dep
  • v1.0.5 - Fixes bug where clean used after set does not honor set's mutation
  • v1.0.1 - v1.0.4 - Readme updates - no code changes
  • v1.0.0 - Hook has been stable in projects, bumping to initial release
  • v0.0.x - Initial dev release - ASSUME UNSTABLE