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 - npm Package Compare versions

Comparing version 3.0.0-alpha.0 to 3.0.0-alpha.1

16

lib/index.d.ts
export interface IFieldValidationState<T> {
errors: string[];
isCue: boolean;
isInvalidCue: boolean;
isDirty: boolean;
isRequired: boolean;
isValid: boolean;
cue: boolean;
cueInvalid: boolean;
dirty: boolean;
required: boolean;
valid: boolean;
label?: string;

@@ -12,9 +12,9 @@ value: T;

export interface IFieldValidation<T> extends IFieldValidationState<T> {
setCue: (isCue: boolean) => void;
setDirty: (isDirty: boolean) => void;
setCue: (cue: boolean) => void;
setDirty: (dirty: boolean) => void;
setValue: (newValue: T) => void;
}
interface ILength {
max?: number;
min?: number;
max?: number;
}

@@ -21,0 +21,0 @@ interface IFieldValidationMessage {

@@ -1,1 +0,1 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const react_1=require("react"),useStateValidate=(e,a)=>{const[s,n]=(0,react_1.useState)(deriveValidateWrapper(e,a)),i=(0,react_1.useRef)(s);let u=(0,react_1.useRef)();const l=e=>{i.current=Object.assign(Object.assign({},i.current),{isCue:e}),i.current.isInvalidCue=i.current.isCue&&!i.current.isValid,n(i.current)};return(0,react_1.useEffect)(()=>()=>{clearTimeout(u.current)},[]),Object.assign(Object.assign({},s),{setCue:l,setDirty:e=>{i.current=Object.assign(Object.assign({},i.current),{isDirty:e}),n(i.current)},setValue:e=>{var t;clearTimeout(u.current);let r=s.isCue;0===a.cueDelay?r=!0:null!=(t=a.cueDelay)&&t&&(r=!1,u.current=setTimeout(()=>{l(!0)},a.cueDelay)),i.current=Object.assign(Object.assign({},deriveValidateWrapper(e,a)),{isCue:r,isDirty:!0}),i.current.isInvalidCue=i.current.isCue&&!i.current.isValid,n(i.current)}})},deriveValidateWrapper=(e,t)=>{var r=validate(e,t);return{errors:r,isCue:!1,isInvalidCue:!1,isDirty:!1,isRequired:Boolean(t.required),isValid:0===r.length,label:null!=(r=t.label)?r:"",value:e}},errorMessage=(e,t)=>{var r,a;if(e.message&&e.message[t])return e.message[t];var s=null!=(r=null==e?void 0:e.label)?r:"value";switch(!0){case/^required$/.test(t):return s+" is required";case/^type$/.test(t):return s+" is not of type "+e[t];case/^length$/.test(t):return`${s} must have a length between ${null==(a=null==e?void 0:e.length)?void 0:a.min} and `+(null==(a=null==e?void 0:e.length)?void 0:a.max);case/^enum$/.test(t):return s+" must be either "+(null==(a=e.enum)?void 0:a.join(", ").replace(/\,(?=[^,]*$)/," or"));case/^match$/.test(t):return s+" does not match pattern "+e[t];case/^(function|fn)$/.test(t):return s+" does not pass function "+e[t]}return"is invalid"},validate=(t,r)=>r.required||""!==t?Object.keys(r).map(e=>{switch(!0){case/^required$/.test(e)&&Boolean(r.required):return validateRequired(t)?"":errorMessage(r,e);case/^length$/.test(e):return validateLength(t,r[e])?"":errorMessage(r,e);case/^enum$/.test(e):return validateEnum(t,r[e])?"":errorMessage(r,e);case/^match[0-9]*$/.test(e):return validateMatch(t,r[e])?"":errorMessage(r,e);case/^fn[0-9]*$/.test(e):return validateFn(t,r[e])?"":errorMessage(r,e)}}).filter(Boolean):[],validateEnum=(e,t)=>-1<t.indexOf(e),validateFn=(e,t)=>t(e),validateLength=(e,t)=>(t.min||0)<=e.length&&e.length<=(t.max||Number.MIN_VALUE),validateMatch=(e,t)=>t.test(e),validateRequired=e=>0===e||Boolean(e);exports.default=useStateValidate;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const react_1=require("react"),useStateValidate=(e,a)=>{const[t,r]=(0,react_1.useState)(deriveValidateWrapper(e,a)),i=(0,react_1.useRef)(t);let l=(0,react_1.useRef)();const n=()=>clearTimeout(l.current),u=e=>{n();var t=i.current["valid"];i.current=Object.assign(Object.assign({},i.current),{cue:e,cueInvalid:e&&!t}),r(i.current)};return(0,react_1.useEffect)(()=>n,[]),Object.assign(Object.assign({},t),{setCue:u,setDirty:e=>{r(Object.assign(Object.assign({},i.current),{dirty:e}))},setValue:e=>{n();let t=i.current["cue"];0===a.cueDelay?t=!0:a.cueDelay&&(t=!1,l.current=setTimeout(()=>{u(!0)},a.cueDelay));e=deriveValidateWrapper(e,a);i.current=Object.assign(Object.assign({},e),{cue:t,dirty:!0,cueInvalid:t&&!e.valid}),r(i.current)}})},deriveValidateWrapper=(e,t)=>{var a=validate(e,t);return{errors:a,cue:!1,valid:0===a.length,cueInvalid:!1,dirty:!1,required:!!t.required,label:t.label||"",value:e}},lengthErrorMessage=({min:e,max:t}={})=>e&&t?`between ${e}-`+t:e?"at least "+e:t?"at most "+t:"",validate=(i,l)=>Object.keys(l).map(e=>{var t=l[e],a=null==(a=null==l?void 0:l.message)?void 0:a[e],r=(null==l?void 0:l.label)||"Field";return"required"===e&&l.required&&!validateRequired(i)?a||r+" is required":"length"!==e||validateLength(i,t)?"enum"!==e||validateEnum(i,t)?/^match[23]*$/.test(e)&&!validateMatch(i,t)?a||r+" match pattern "+t:/^fn[23]*$/.test(e)&&!validateFn(i,t)?a||r+" does not pass function "+t:void 0:a||r+" must be either "+(null==(e=l.enum)?void 0:e.join(", ").replace(/\,(?=[^,]*$)/," or")):a||`${r} must be ${lengthErrorMessage(null==l?void 0:l.length)} characters`}).filter(Boolean),validateEnum=(e,t)=>-1<t.indexOf(e),validateFn=(e,t)=>t(e),validateLength=(e,t)=>(t.min||0)<=e.length&&e.length<=(t.max||Number.MIN_VALUE),validateMatch=(e,t)=>t.test(e),validateRequired=e=>0===e||!!e;exports.default=useStateValidate;
{
"name": "use-state-validate",
"version": "3.0.0-alpha.0",
"description": "Custom hook to account for state and validation off single state value",
"version": "3.0.0-alpha.1",
"description": "Clean featherweight state validation",
"sideEffects": false,
"license": "MIT",

@@ -49,2 +50,3 @@ "publishConfig": {

"@testing-library/react": "^11.2.7",
"@testing-library/react-hooks": "^8.0.1",
"@types/jest": "^26.0.24",

@@ -51,0 +53,0 @@ "@types/react": "^16.14.34",

@@ -35,3 +35,3 @@ # use-state-validate

console.log(nameV.value); // Tim
console.log(nameV.isValid); // false
console.log(nameV.valid); // false
```

@@ -41,28 +41,24 @@

const [`<fieldStates>`, `<fieldActions>`] = useStateValidate(`<initVal>`, `<rules>`)
const `fieldObject` = useStateValidate(`initialState`, `ruleObject`)
`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.
`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.
`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)
`rulesObject` - An object with rule configuration options
* `value` - Flagged as true when valid and false when invalid. This is the absolute truth regarding a
| | |
| --------------- | ---- |
| `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

@@ -92,5 +88,5 @@ ```

"name": "label given to wrapper",
"isDirty": false,
"isRequired": true,
"isValid": false,
"dirty": false,
"required": true,
"valid": false,
"type": "string",

@@ -97,0 +93,0 @@ "errors": [

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