New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

use-state-validate

Package Overview
Dependencies
Maintainers
1
Versions
59
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-state-validate

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

  • 1.0.5
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
40K
decreased by-18.08%
Maintainers
1
Weekly downloads
 
Created
Source

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
  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.

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 [<valWrap>, <setVal>, <cleanVal>] = useStateValidate(<initVal>, <rules>)

valWrapAn object containing the raw value and validation data, use <valWrap>.value to get the value
setValSet function, that behaves like useState. PLEASE PASS THE RAW VALUE HERE, not a wrapper like object!
cleanValFunction to clean the dirty flag. The dirty flag defaults to false, but is set to true if setVal is invoked
initValThe initial value to start with
rulesA 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!"
  }
}

Illustration of valueWrapped, showing the validation wrapper 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 [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>
  );
};

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
v1.0.0 - Hook has been stable in projects, bumping to initial release
v1.0.1 - v1.0.4 - Readme updates - no code changes
v1.0.5 - Fixes bug where clean used after set does not honor set's mutation

Keywords

FAQs

Package last updated on 11 Sep 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc