JSPM

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

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

Package Exports

  • use-state-validate

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

⚠️ **PRE - RELEASE **: This should not be used in production, play at your own risk.

Version npm

NPM

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

npm install use-state-validate --save-dev
  import useStateValidate from 'use-state-validate';
  // or
  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 😀

Also, please consult validate at https://www.npmjs.com/package/validate for possible rules to use.

Hook Signature

const [<valueWrapped>, <setValue>, <cleanValue>] = useStateValidate(<initialValue>, <rules>)

valueWrapped An object containing the raw value and validation data, use <valueWrapped>.value to get the value
setValue Set function, that behaves like useState. PLEASE PASS THE RAW VALUE HERE, not a wrapper like object!
cleanValue Function to clean the dirty flag. The dirty flag defaults to false, but is set to true if setValue is invoked
initialValue The initial value to start with
rules A mostly flat object using rules found at https://www.npmjs.com/package/validate

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!"
  }
}

Example of valueWrapped, showing the validation data object

{
  "value": "value of field",
  "isDirty": false,
  "isValid": false,
  "errorMessages": [
    "Error Message 1",
    "Error Message 2"
  ]
}

Basic Usage

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

const Component: React.FC = () => {
  const [name, 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>{name.value}</span>
      </label>
      <hr />
      <input value={name.value} onChange={(evt) => setName(evt.target.value)}/>
      <button onClick={cleanName}>Clean it</button>
      <hr />
      <div> ⬇️ Show Me the Data! ⬇️ </div>
      <pre>{JSON.stringify(name, null, 2)}</pre>
    </section>
  );
};

Credit to Key Dependency Author

Many thanks to Eivind Fjeldstad for creating the package, validate, which this hook uses for the validation engine. Check out the package here → https://www.npmjs.com/package/validate

Changelog

v0.0.x - Initial dev release - ASSUME UNSTABLE