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

@iwsio/forms

Package Overview
Dependencies
Maintainers
1
Versions
51
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@iwsio/forms - npm Package Compare versions

Comparing version 0.1.4 to 0.2.1

dist/FieldManager.d.ts

20

dist/index.d.ts

@@ -1,13 +0,9 @@

declare namespace _default {
export { CheckboxInput };
export { TextInput };
export { TextArea };
export { ValidatedForm };
}
export default _default;
import CheckboxInput from "./checkbox";
import TextInput from "./text-input";
import TextArea from "./textarea";
import ValidatedForm from "./validated-form";
export { CheckboxInput, TextInput, TextArea, ValidatedForm };
export * from './Input';
export * from './Select';
export * from './TextArea';
export * from './types';
export * from './FieldManager';
export * from './useFieldState';
export * from './useForwardRef';
export * from './ValidatedForm';
//# sourceMappingURL=index.d.ts.map

27

dist/index.js

@@ -1,2 +0,25 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"CheckboxInput",{enumerable:true,get:function get(){return _checkbox.default}});Object.defineProperty(exports,"TextArea",{enumerable:true,get:function get(){return _textarea.default}});Object.defineProperty(exports,"TextInput",{enumerable:true,get:function get(){return _textInput.default}});Object.defineProperty(exports,"ValidatedForm",{enumerable:true,get:function get(){return _validatedForm.default}});exports.default=void 0;var _checkbox=_interopRequireDefault(require("./checkbox"));var _textInput=_interopRequireDefault(require("./text-input"));var _textarea=_interopRequireDefault(require("./textarea"));var _validatedForm=_interopRequireDefault(require("./validated-form"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var _default={CheckboxInput:_checkbox.default,TextInput:_textInput.default,TextArea:_textarea.default,ValidatedForm:_validatedForm.default};exports.default=_default;
//# sourceMappingURL=index.js.map
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./Input"), exports);
__exportStar(require("./Select"), exports);
__exportStar(require("./TextArea"), exports);
__exportStar(require("./types"), exports);
__exportStar(require("./FieldManager"), exports);
__exportStar(require("./useFieldState"), exports);
__exportStar(require("./useForwardRef"), exports);
__exportStar(require("./ValidatedForm"), exports);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLDBDQUF1QjtBQUN2QiwyQ0FBd0I7QUFDeEIsNkNBQTBCO0FBQzFCLDBDQUF1QjtBQUN2QixpREFBOEI7QUFDOUIsa0RBQStCO0FBQy9CLGtEQUErQjtBQUMvQixrREFBK0IifQ==

@@ -1,15 +0,9 @@

import React, { HTMLProps } from "react";
export interface TextInputProps {
error?: string;
validationMessageComponent?: JSX.Element;
}
export declare type TextInput = React.Component<TextInputProps & React.Component<HTMLProps<HTMLInputElement>>>;
export interface ValidatedFormProps {
onValidSubmit: () => void;
onReset?: () => void;
reportValidity?: boolean;
}
export declare type ValidatedForm = React.Component<ValidatedFormProps & React.HTMLProps<HTMLFormElement>>;
export declare type ValidatedFormForwardRef = React.ForwardRefExoticComponent<React.RefAttributes<ValidatedForm>>;
export declare type TextInputForwardRef = React.ForwardRefExoticComponent<React.RefAttributes<TextInputProps>>;
import { ReactNode } from 'react';
export type ChildrenProp = {
children?: ReactNode;
};
export type ValidationProps = {
fieldError?: string;
onFieldError?: (key: string, message?: string) => void;
};
//# sourceMappingURL=types.d.ts.map
{
"name": "@iwsio/forms",
"version": "0.1.4",
"version": "0.2.1",
"description": "Simple library with useful React forms components and browser validation.",
"main": "dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": "./dist/index.js",
"./*": "./dist/*.js"
},
"files": [
"./dist"
],
"scripts": {
"test": "jest --verbose",
"prebuild": "rimraf dist samples/dist",
"build": "npm-run-all build:*",
"build:js": "babel src --out-dir dist --minified --no-comments --source-maps --compact --ignore \"test/**/*\",\"**/*.test.js\"",
"build:ts": "tsc"
"test": "VITEST_SEGFAULT_RETRY=3 vitest --run --passWithNoTests",
"prebuild": "tsc --build tsconfig.build.json --clean && rimraf dist",
"build": "tsc --build tsconfig.build.json",
"watch": "npm run build -- --watch"
},

@@ -32,38 +38,32 @@ "repository": {

"homepage": "https://github.com/iwsllc/iws-forms#readme",
"browserslist": [
"defaults"
],
"devDependencies": {
"@babel/cli": "^7.17.6",
"@babel/core": "^7.17.5",
"@babel/eslint-parser": "^7.17.0",
"@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.16.7",
"@babel/register": "^7.17.0",
"@babel/runtime": "^7.17.2",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.0.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.0.4",
"@types/jest": "^27.4.1",
"babel-jest": "^27.5.1",
"@types/node": "^18.16.13",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.10",
"@typescript-eslint/eslint-plugin": "^5.39.0",
"@typescript-eslint/parser": "^5.39.0",
"eslint": "^8.10.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jest": "^26.1.1",
"eslint-import-resolver-typescript": "^3.5.5",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-react": "^7.29.3",
"jest": "^27.5.1",
"jsdom": "^22.0.0",
"lodash.defaults": "^4.2.0",
"lodash.isnull": "^3.0.0",
"lodash.omitby": "^4.6.0",
"npm-run-all": "^4.1.5",
"prop-types": "^15.8.1",
"regenerator-runtime": "^0.13.9",
"ts-node": "^10.7.0",
"typescript": "^4.6.2"
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rimraf": "^5.0.0",
"tslib": "^2.4.1",
"typescript": "^5.0.2",
"vitest": "^0.31.0"
},
"peerDependencies": {
"@babel/runtime": "*",
"react": "^18"
},
"dependencies": {
"react": "^18.0.0"
}
}

@@ -5,34 +5,84 @@ # @iwsio/forms

This is just a basic module to simplify the use of browser validation in forms with React. This package is **incomplete**. I've pretty much only worked with/tested `TextInput` for demos. If there is any interest in this, I'll continue to improve and expand it.
I found myself recreating similar code in every proejct I worked on that performed the simple task of local state management with controlled inputs and client validation. So I abstracted it out into this library for re-use.
## MDN Forms validation
https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation
## Install
- `npm install @iwsio/forms`
- `yarn install @iwsio/forms`
- `pnpm install @iwsio/forms`
## Controlled inputs: `<Input />`, `<Select />`, and `<TextArea />`
These controlled inputs allow you to track error state with a controlled value. They are identical to (and pass along) all the props from their counterparts `input`, `select` and `textarea`. These means you can use regular HTML 5 browser validation AND you can set custom errors easily with React state and let browser validation do the work of reporting or checking for invalid fields. These components include: `Input`, `Select`, and `TextArea` and work exactly how native elements work, the key difference being: you can include a `fieldError` and `onFieldError` props to manage error state.
## Example
## `<ValidatedForm>`
Complimenting this, I've included a simple form component to simplify styling and success submit handling. It includes some CSS sugar `needs-validation` and `was-validated` for pre and post first submission. (This is kind of a throwback to Bootstrap, but you can use it however you like).
`onSubmit` invokes when form submit happens with all valid inputs. It's the same as using a regular `<form/>` `onSubmit` but with a built-in `form.checkValidity()` call to ensure field inputs are valid.
```jsx
<ValidatedForm onValidSubmit={() => {/* Calls on submit if form is valid. */}}>
<label className="form-label" for="name">Name</label>
<TextInput name="name" required pattern="^\a+$" validationMessageComponent={<div className="form-text invalid-feedback" />} />
<p className="mt-3">
<button type="submit" className="btn btn-primary">Submit</button>
</p>
</ValidatedForm>
const Sample = () => {
const handleSubmit = () => {
// Form is valid; fields are safe to consume here.
}
return (
<ValidatedForm onSubmit={handleSubmit}>
<Input type="text" name="field1" required pattern="^\w+$" />
</ValidatedForm>
)
}
```
### Renders HTML (always)
As the validation events trigger in the browser, the component is listening for these and updating the validation message for the input. This was kind of built with Bootstrap 4/5 in mind where class names drive visibility of those validation states. i.e. `invalid-feedback` will not be visible unless the form `was-validated` and the field is in a state that is `:invalid`.
```html
<form class=" was-validated" novalidate="">
<label class="form-label" for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" required="" value="">
<div class="form-text invalid-feedback" data-testid="text-input-name-child-0"></div>
</form>
### Renders:
#### Before submit
```jsx
<form class="needs-validation">
<input type="text" name="field1" required pattern="^\w+$" value="" />
</form>
```
#### After submit
```jsx
<form class="was-validated">
<input type="text" name="field1" required pattern="^\w+$" value="" />
</form>
```
### When invalid:
```html
<div class="form-text invalid-feedback" data-testid="text-input-name-child-0">Please fill out this field.</div>
## `useFieldState`
Next there is a `useFieldState` hook, which manages all the field value and error states for a form. This can be used independent of all the other components. The idea is to simply use a `Record<string,string>` type of state where the keys are the field names and their values, the value. It manages both `values` and `errors` and provides methods to hook into that and make custom updates.
```jsx
const Sample = () => {
const { fields, onChange } = useFieldState({field1: ''})
return (
<form>
<input type="text" name="field1" required pattern="^\w+$" onChange={onChange} value={fields.field1} />
</form>
)
}
```
## See [Demo Readme](./demo/README.md) for testing this out locally.
## `<FieldManager>`
Finally, it's brought all together with `FieldManager`. This provider is used to automatically wire up components into the field state and hook up form validation and onChange events. Rather than using the default `Input`, `Select` and `TextArea` components, you'll use extensions of those: `InputField`, `SelectField`, and `TextAreaField` respectively to further simplify your code. Here is a quick example:
```jsx
const Sample = () => {
const fieldState = useFieldState({field1: '', field2: '', field3: ''})
return (
<FieldManager form={fieldState}>
<ValidatedForm>
<InputField type="text" name="field1" required pattern="^\w+$" />
<InputField type="number" name="field2" required min={0} max={10} step={1} />
<InputField type="phone" name="field3" required />
<button type="submit">Submit</button>
</ValidatedForm>
</FieldManager>
)
}
```
## References:
### MDN Forms validation
https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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