JSPM

  • Created
  • Published
  • Downloads 28579
  • Score
    100M100P100Q158584F
  • License MIT

Clean featherweight state validation

Package Exports

  • use-state-validate

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.valid); // false

Hook Signature

const fieldObject = useStateValidate(initialState, ruleObject)

fieldObject - An object wrapping the value and relevant flags

  • value - Flagged as true when valid and false when invalid. This is the absolute truth regarding a fields validity based on the provided rules.
  • label - Label from the rules object that is projected out, useful for adding to input labels.
  • valid - Flagged as true when valid and false when invalid. This is the absolute truth regarding a fields validity based on the provided rules.
  • cue - (Default: false) - A flag for cueing your users to fix validation errors. Use in conjunction with valid to display error states to users. The aim is gently remind your users to correct mistakes after they are made instead of prematurely yelling at them when data entry is in progress.
  • cueInvalid - A convenience alias for the expression cue && !valid. In plain terms: the field is invalid and user should be messaged when this flag is true. Use this for error display logic. The flag cueInvalid can also be thought of as computed and cannot be directly modified like cue.
  • dirty - (Default: false) - Flagged as true when the field is modified via the setValue() function. Some libraries use a pristine flag, dirty is the negation of pristine and can be used in the same capacity. Extra bytes are not spent in creating an alias on this one. cue is preferred for error presentation logic. The dirty flag's role is to track whether or not a field was modified.
  • required - (Default: false) - Flag from the rules object that is projected back out, useful for visually annotating that fields are "required".
  • errors - A string array of error messages that resulted from validation failures. Use errors[0] to grab the first error message.
  • setValue - Modifies the field's value. Analogous to setState(). (via setState)
  • setClean - Marks the field as cued or not cued. Updates the value of cue.
  • setDirty - Marks the field as dirty or not dirty. Updates the value of dirty.

rulesObject - An object with rule configuration options

  • value - Flagged as true when valid and false when invalid. This is the absolute truth regarding a

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",
  "dirty": false,
  "required": true,
  "valid": 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