react-mui-form-validator 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 blencm
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2022 blencm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/Readme.md CHANGED
@@ -1,144 +1,219 @@
1
- ## Validation component for material-ui forms
2
-
3
- [![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://opensource.org/licenses/MIT)
4
-
5
- ### Installation
6
-
7
- ```
8
- npm install react-mui-form-validator
9
-
10
- ```
11
-
12
- ### Info
13
-
14
- Some rules can accept extra parameter, example:
15
-
16
- TextField
17
- ```javascript
18
- <MuiTextField
19
- {...someProps}
20
- validators={["minNumber:0", "maxNumber:255", "matchRegexp:^[0-9]$"]}
21
- />
22
- ```
23
-
24
- ### Usage Example
25
-
26
- You can pass any props of field components, but note that `errorText` prop will be replaced when validation errors occurred.
27
- Your component must [provide a theme](http://www.material-ui.com/#/get-started/usage).
28
-
29
- ```javascript
30
- import React from "react";
31
- import Button from "@mui/material/Button";
32
- import { MuiForm, MuiTextField } from "react-mui-form-validator";
33
-
34
- class MyForm extends React.Component {
35
- state = {
36
- email: "",
37
- };
38
-
39
- handleChange = (event) => {
40
- const email = event.target.value;
41
- this.setState({ email });
42
- };
43
-
44
- handleSubmit = () => {
45
- // your submit logic
46
- };
47
-
48
- render() {
49
- const { email } = this.state;
50
- return (
51
- <MuiForm
52
- onSubmit={this.handleSubmit}
53
- onError={(errors) => console.log(errors)}
54
- >
55
- <MuiTextField
56
- label="Email"
57
- onChange={this.handleChange}
58
- name="email"
59
- value={email}
60
- validators={["required", "isEmail"]}
61
- errorMessages={["this field is required", "email is not valid"]}
62
- />
63
- <Button type="submit">Submit</Button>
64
- </MuiForm>
65
- );
66
- }
67
- }
68
- ```
69
-
70
- You can add your custom rules:
71
-
72
- ```javascript
73
-
74
- import React from 'react';
75
- import Button from '@mui/material/Button';
76
- import { MuiForm, MuiTextField} from 'react-mui-form-validator';
77
-
78
- class ResetPasswordForm extends React.Component {
79
-
80
- state = {
81
- user: {
82
- password: '',
83
- repeatPassword: '',
84
- },
85
- };
86
-
87
- componentDidMount() {
88
- // custom rule will have name 'isPasswordMatch'
89
- MuiForm.addValidationRule('isPasswordMatch', (value) => {
90
- if (value !== this.state.user.password) {
91
- return false;
92
- }
93
- return true;
94
- });
95
- }
96
-
97
- componentWillUnmount() {
98
- // remove rule when it is not needed
99
- MuiForm.removeValidationRule('isPasswordMatch');
100
- }
101
-
102
- handleChange = (event) => {
103
- const { user } = this.state;
104
- user[event.target.name] = event.target.value;
105
- this.setState({ user });
106
- }
107
-
108
- handleSubmit = () => {
109
- // your submit logic
110
- }
111
-
112
- render() {
113
- const { user } = this.state;
114
-
115
- return (
116
- <MuiForm
117
- onSubmit={this.handleSubmit}
118
- >
119
- <MuiTextField
120
- label="Password"
121
- onChange={this.handleChange}
122
- name="password"
123
- type="password"
124
- validators={['required']}
125
- errorMessages={['this field is required']}
126
- value={user.password}
127
- />
128
- <MuiTextField
129
- label="Repeat password"
130
- onChange={this.handleChange}
131
- name="repeatPassword"
132
- type="password"
133
- validators={['isPasswordMatch', 'required']}
134
- errorMessages={['password mismatch', 'this field is required']}
135
- value={user.repeatPassword}
136
- />
137
- <Button type="submit">Submit</Button>
138
- </MuiForm>
139
- );
140
- }
141
-
142
- ```
143
-
144
- ##### [Advanced usage](https://github.com/blencm/react-mui-form-validator/wiki)
1
+ ## Validation component for material-ui forms
2
+
3
+ [![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ ### Installation
6
+
7
+ ```
8
+ npm install react-mui-form-validator
9
+
10
+ ```
11
+
12
+ ### Info
13
+
14
+ Some rules can accept extra parameter, example:
15
+
16
+ TextField
17
+ ```javascript
18
+ <MuiTextField
19
+ {...someProps}
20
+ validators={["minNumber:0", "maxNumber:255", "matchRegexp:^[0-9]$"]}
21
+ />
22
+ ```
23
+
24
+ ### Usage Example
25
+
26
+ You can pass any props of field components, but note that `errorText` prop will be replaced when validation errors occurred.
27
+ Your component must [provide a theme](http://www.material-ui.com/#/get-started/usage).
28
+
29
+ ```javascript
30
+
31
+ import { useState } from "react";
32
+ import "./App.css";
33
+ import { MuiForm, MuiTextField } from "react-mui-form-validator";
34
+ import { Button, IconButton, InputAdornment, Paper } from "@mui/material";
35
+ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
36
+ import {
37
+ faEnvelope,
38
+ faEye,
39
+ faEyeSlash,
40
+ } from "@fortawesome/free-solid-svg-icons";
41
+
42
+ export default function App(props: any) {
43
+ const [name, setName] = useState();
44
+ const [email, setEmail] = useState();
45
+ const [password, setPassword] = useState();
46
+ const [showPassword, setShowPassword] = useState(false);
47
+
48
+ const changeName = (event: any) => {
49
+ const name = event.target.value;
50
+ setName(name);
51
+ };
52
+
53
+ const changeEmail = (event: any) => {
54
+ const email = event.target.value;
55
+ setEmail(email);
56
+ };
57
+
58
+ const changePassword = (event: any) => {
59
+ const password = event.target.value;
60
+ setPassword(password);
61
+ };
62
+
63
+ const handleSubmit = () => {
64
+ // your submit logic
65
+ };
66
+
67
+ return (
68
+ <div className="App">
69
+ <center>
70
+ <Paper className="container">
71
+ <h3>Example Sign In</h3>
72
+ <MuiForm
73
+ onSubmit={handleSubmit}
74
+ onError={(errors: any) => console.log(errors)}
75
+ >
76
+ <MuiTextField
77
+ name="name"
78
+ //className="css-style-name" add your css style
79
+ //classes={classes.emailInput} //add your js or ts style
80
+ label="Name"
81
+ placeholder="Name"
82
+ onChange={changeName}
83
+ value={name}
84
+ validators={["required"]}
85
+ errorMessages={["this field is required"]}
86
+ fullWidth
87
+ />
88
+ <br />
89
+ <MuiTextField
90
+ name="email"
91
+ //className="css-style-name" add your css style
92
+ //classes={classes.emailInput} //add your js or ts style
93
+ label="Email"
94
+ placeholder="Email"
95
+ onChange={changeEmail}
96
+ value={email}
97
+ validators={["required", "isEmail"]}
98
+ errorMessages={["this field is required", "email is not valid"]}
99
+ InputProps={{
100
+ startAdornment: (
101
+ <InputAdornment position="start">
102
+ <FontAwesomeIcon icon={faEnvelope} />
103
+ </InputAdornment>
104
+ ),
105
+ }}
106
+ fullWidth
107
+ />
108
+ <br />
109
+ <MuiTextField
110
+ type={showPassword ? "text" : "password"}
111
+ style={{ marginBottom: 0 }}
112
+ name="password"
113
+ label="Password"
114
+ //InputLabelProps={{ shrink: true }}
115
+ placeholder="Password"
116
+ value={password}
117
+ onChange={changePassword}
118
+ InputProps={{
119
+ startAdornment: (
120
+ <InputAdornment position="start">
121
+ <FontAwesomeIcon icon={faEnvelope} />
122
+ </InputAdornment>
123
+ ),
124
+ endAdornment: (
125
+ <InputAdornment position="end">
126
+ <IconButton
127
+ aria-label="toggle password visibility"
128
+ onClick={() => setShowPassword(!showPassword)}
129
+ onMouseDown={(e) => e.preventDefault()}
130
+ edge="end"
131
+ >
132
+ <FontAwesomeIcon
133
+ icon={showPassword ? faEyeSlash : faEye}
134
+ />
135
+ </IconButton>
136
+ </InputAdornment>
137
+ ),
138
+ }}
139
+ validators={["required"]}
140
+ errorMessages={["Password is required"]}
141
+ variant="outlined"
142
+ fullWidth
143
+ />
144
+ <br />
145
+ <Button type="submit" variant="outlined">
146
+ Sign In
147
+ </Button>
148
+ </MuiForm>
149
+ </Paper>
150
+ </center>
151
+ </div>
152
+ );
153
+ }
154
+
155
+ ```
156
+ css style example:
157
+
158
+ ```
159
+ .App {
160
+ text-align: center;
161
+ width: 100%;
162
+ }
163
+
164
+ .container {
165
+ width: 500px;
166
+ height: auto;
167
+ background: #FFFFFF;
168
+ box-shadow: 0px 20px 56px rgba(0, 0, 0, 0.1);
169
+ border-radius: 16px;
170
+ padding: 15px;
171
+ margin: 20px;
172
+ }
173
+
174
+ ```
175
+
176
+ Class component example:
177
+
178
+ ```javascript
179
+
180
+ import React from "react";
181
+ import Button from "@mui/material/Button";
182
+ import { MuiForm, MuiTextField } from "react-mui-form-validator";
183
+
184
+ class MyForm extends React.Component {
185
+ state = {
186
+ email: "",
187
+ };
188
+
189
+ handleChange = (event) => {
190
+ const email = event.target.value;
191
+ this.setState({ email });
192
+ };
193
+
194
+ handleSubmit = () => {
195
+ // your submit logic
196
+ };
197
+
198
+ render() {
199
+ const { email } = this.state;
200
+ return (
201
+ <MuiForm
202
+ onSubmit={this.handleSubmit}
203
+ onError={(errors) => console.log(errors)}
204
+ >
205
+ <MuiTextField
206
+ label="Email"
207
+ onChange={this.handleChange}
208
+ name="email"
209
+ value={email}
210
+ validators={["required", "isEmail"]}
211
+ errorMessages={["this field is required", "email is not valid"]}
212
+ />
213
+ <Button type="submit">Submit</Button>
214
+ </MuiForm>
215
+ );
216
+ }
217
+ }
218
+
219
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-mui-form-validator",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "Validator for forms designed with material-ui components.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -14,6 +14,7 @@
14
14
  "keywords": [
15
15
  "react",
16
16
  "mui",
17
+ "material-ui",
17
18
  "form",
18
19
  "form-validator",
19
20
  "validator"
@@ -27,14 +28,10 @@
27
28
  "dependencies": {
28
29
  "@mui/material": "^5.13.6",
29
30
  "@types/prop-types": "^15.7.5",
30
- "gud": "^1.0.0",
31
- "promise-polyfill": "^8.3.0",
32
31
  "prop-types": "^15.8.1",
33
32
  "react": "^18.2.0",
34
33
  "react-dom": "^18.2.0",
35
- "react-hook-form": "^7.45.1",
36
34
  "react-lifecycles-compat": "^3.0.4",
37
- "tiny-warning": "^1.0.3",
38
35
  "tsup": "^7.1.0",
39
36
  "typescript": "^5.1.6",
40
37
  "warning": "^4.0.3"
@@ -45,7 +42,6 @@
45
42
  },
46
43
  "devDependencies": {
47
44
  "@types/node": "^20.3.3",
48
- "@types/promise-polyfill": "^6.0.4",
49
45
  "@types/react": "18.2.14",
50
46
  "@types/react-dom": "^18.2.6",
51
47
  "@types/react-lifecycles-compat": "^3.0.1",
@@ -59,7 +55,6 @@
59
55
  "eslint-plugin-jsx-a11y": "^6.7.1",
60
56
  "eslint-plugin-prettier": "4.2.1",
61
57
  "eslint-plugin-react": "^7.32.2",
62
- "eslint-plugin-react-hooks": "^4.6.0",
63
- "rimraf": "^5.0.1"
58
+ "eslint-plugin-react-hooks": "^4.6.0"
64
59
  }
65
60
  }
package/tsconfig.json CHANGED
@@ -1,26 +1,26 @@
1
- {
2
- "compilerOptions": {
3
- "module": "commonjs",
4
- "target": "es2022",
5
-
6
- "strict": true,
7
- "esModuleInterop": true,
8
- "skipLibCheck": true,
9
- "forceConsistentCasingInFileNames": true,
10
-
11
- "lib": ["es2022", "dom", "dom.iterable", "esnext"],
12
- "allowJs": true,
13
- "allowSyntheticDefaultImports": true,
14
- "noFallthroughCasesInSwitch": true,
15
-
16
- "outDir": "dist",
17
- "declaration": true,
18
- "moduleResolution": "node",
19
- "resolveJsonModule": true,
20
- "isolatedModules": true,
21
- "noEmit": true,
22
- "jsx": "react"
23
- },
24
-
25
- "include": ["src/**/*"]
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "target": "es2022",
5
+
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "skipLibCheck": true,
9
+ "forceConsistentCasingInFileNames": true,
10
+
11
+ "lib": ["es2022", "dom", "dom.iterable", "esnext"],
12
+ "allowJs": true,
13
+ "allowSyntheticDefaultImports": true,
14
+ "noFallthroughCasesInSwitch": true,
15
+
16
+ "outDir": "dist",
17
+ "declaration": true,
18
+ "moduleResolution": "node",
19
+ "resolveJsonModule": true,
20
+ "isolatedModules": true,
21
+ "noEmit": true,
22
+ "jsx": "react"
23
+ },
24
+
25
+ "include": ["src/**/*"]
26
26
  }
package/dist/index.d.ts DELETED
@@ -1,122 +0,0 @@
1
- import React from 'react';
2
- import PropTypes from 'prop-types';
3
-
4
- declare class ValidatorComponent extends React.Component<any, any, any> {
5
- static getDerivedStateFromProps(nextProps: any, prevState: any): {
6
- value: any;
7
- validators: any;
8
- errorMessages: any;
9
- } | {
10
- value: any;
11
- validators?: undefined;
12
- errorMessages?: undefined;
13
- };
14
- constructor(props: any);
15
- constructor(props: any, context: any);
16
- state: {
17
- isValid: boolean;
18
- value: any;
19
- errorMessages: any;
20
- validators: any;
21
- };
22
- componentDidMount(): void;
23
- shouldComponentUpdate(nextProps: any, nextState: any): boolean;
24
- componentDidUpdate(prevProps: any, prevState: any): void;
25
- componentWillUnmount(): void;
26
- getErrorMessage: () => any;
27
- instantValidate: boolean;
28
- invalid: any[];
29
- configure: () => void;
30
- debounceTime: any;
31
- validateDebounced: {
32
- (value?: any, includeRequired?: boolean | undefined, dryRun?: boolean | undefined): void;
33
- cancel: () => void;
34
- } | undefined;
35
- validate: (value: any, includeRequired?: boolean, dryRun?: boolean) => Promise<boolean>;
36
- isValid: () => boolean;
37
- makeInvalid: () => void;
38
- makeValid: () => void;
39
- renderComponent: (form: any) => any;
40
- form: any;
41
- render(): React.JSX.Element;
42
- }
43
- declare namespace ValidatorComponent {
44
- namespace propTypes {
45
- let errorMessages: PropTypes.Requireable<NonNullable<string | any[] | null | undefined>>;
46
- let validators: PropTypes.Requireable<any[]>;
47
- let value: PropTypes.Requireable<any>;
48
- let validatorListener: PropTypes.Requireable<(...args: any[]) => any>;
49
- let withRequiredValidator: PropTypes.Requireable<boolean>;
50
- let containerProps: PropTypes.Requireable<object>;
51
- }
52
- namespace defaultProps {
53
- let errorMessages_1: string;
54
- export { errorMessages_1 as errorMessages };
55
- let validators_1: never[];
56
- export { validators_1 as validators };
57
- export function validatorListener_1(): void;
58
- export { validatorListener_1 as validatorListener };
59
- }
60
- }
61
-
62
- declare class TextValidator extends ValidatorComponent {
63
- renderValidatorComponent(): React.JSX.Element;
64
- }
65
-
66
- declare class MuiSelect$1 extends ValidatorComponent {
67
- renderValidatorComponent(): React.JSX.Element;
68
- }
69
-
70
- declare class ValidatorForm extends React.Component<any, any, any> {
71
- static getValidator: (validator: any, value: any, includeRequired: any) => boolean;
72
- constructor(props: any);
73
- constructor(props: any, context: any);
74
- getFormHelpers: () => {
75
- form: {
76
- attachToForm: (component: any) => void;
77
- detachFromForm: (component: any) => void;
78
- instantValidate: any;
79
- debounceTime: any;
80
- };
81
- };
82
- instantValidate: any;
83
- debounceTime: any;
84
- childs: any[];
85
- errors: any[];
86
- attachToForm: (component: any) => void;
87
- detachFromForm: (component: any) => void;
88
- submit: (event: any) => void;
89
- walk: (children: any, dryRun: any) => Promise<any>;
90
- checkInput: (input: any, dryRun: any) => Promise<any>;
91
- validate: (input: any, includeRequired: any, dryRun: any) => Promise<any>;
92
- find: (collection: any, fn: any) => any;
93
- resetValidations: () => void;
94
- isFormValid: (dryRun?: boolean) => Promise<any>;
95
- render(): React.JSX.Element;
96
- }
97
- declare namespace ValidatorForm {
98
- function addValidationRule(name: any, callback: any): void;
99
- function getValidationRule(name: any): any;
100
- function hasValidationRule(name: any): any;
101
- function removeValidationRule(name: any): void;
102
- namespace propTypes {
103
- let onSubmit: PropTypes.Validator<(...args: any[]) => any>;
104
- let instantValidate: PropTypes.Requireable<boolean>;
105
- let children: PropTypes.Requireable<PropTypes.ReactNodeLike>;
106
- let onError: PropTypes.Requireable<(...args: any[]) => any>;
107
- let debounceTime: PropTypes.Requireable<number>;
108
- }
109
- namespace defaultProps {
110
- export function onError_1(): void;
111
- export { onError_1 as onError };
112
- let debounceTime_1: number;
113
- export { debounceTime_1 as debounceTime };
114
- }
115
- }
116
-
117
- declare const MuiTextField: typeof TextValidator;
118
- declare const MuiSelect: typeof MuiSelect$1;
119
- declare const MuiComponent: typeof ValidatorComponent;
120
- declare const MuiForm: typeof ValidatorForm;
121
-
122
- export { MuiComponent, MuiForm, MuiSelect, MuiTextField };
package/dist/index.js DELETED
@@ -1,601 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // src/core/validator/ValidationRules.jsx
34
- var require_ValidationRules = __commonJS({
35
- "src/core/validator/ValidationRules.jsx"(exports, module2) {
36
- "use strict";
37
- var isExisty = function(value) {
38
- return value !== null && value !== void 0;
39
- };
40
- var isEmpty = function(value) {
41
- if (value instanceof Array) {
42
- return value.length === 0;
43
- }
44
- return value === "" || !isExisty(value);
45
- };
46
- var isEmptyTrimed = function(value) {
47
- if (typeof value === "string") {
48
- return value.trim() === "";
49
- }
50
- return true;
51
- };
52
- var validations = {
53
- matchRegexp: (value, regexp) => {
54
- const validationRegexp = regexp instanceof RegExp ? regexp : new RegExp(regexp);
55
- return isEmpty(value) || validationRegexp.test(value);
56
- },
57
- // eslint-disable-next-line
58
- isEmail: (value) => validations.matchRegexp(value, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i),
59
- isEmpty: (value) => isEmpty(value),
60
- required: (value) => !isEmpty(value),
61
- trim: (value) => !isEmptyTrimed(value),
62
- isNumber: (value) => validations.matchRegexp(value, /^-?[0-9]\d*(\d+)?$/i),
63
- isFloat: (value) => validations.matchRegexp(value, /^(?:-?[1-9]\d*|-?0)?(?:\.\d+)?$/i),
64
- isPositive: (value) => {
65
- if (isExisty(value)) {
66
- return (validations.isNumber(value) || validations.isFloat(value)) && value >= 0;
67
- }
68
- return true;
69
- },
70
- maxNumber: (value, max) => isEmpty(value) || parseInt(value, 10) <= parseInt(max, 10),
71
- minNumber: (value, min) => isEmpty(value) || parseInt(value, 10) >= parseInt(min, 10),
72
- maxFloat: (value, max) => isEmpty(value) || parseFloat(value) <= parseFloat(max),
73
- minFloat: (value, min) => isEmpty(value) || parseFloat(value) >= parseFloat(min),
74
- isString: (value) => isEmpty(value) || typeof value === "string" || value instanceof String,
75
- minStringLength: (value, length) => validations.isString(value) && value.length >= length,
76
- maxStringLength: (value, length) => validations.isString(value) && value.length <= length,
77
- // eslint-disable-next-line no-undef
78
- isFile: (value) => isEmpty(value) || value instanceof File,
79
- maxFileSize: (value, max) => isEmpty(value) || validations.isFile(value) && value.size <= parseInt(max, 10),
80
- allowedExtensions: (value, fileTypes) => isEmpty(value) || validations.isFile(value) && fileTypes.split(",").indexOf(value.type) !== -1
81
- };
82
- module2.exports = validations;
83
- }
84
- });
85
-
86
- // src/index.ts
87
- var src_exports = {};
88
- __export(src_exports, {
89
- MuiComponent: () => MuiComponent,
90
- MuiForm: () => MuiForm,
91
- MuiSelect: () => MuiSelect2,
92
- MuiTextField: () => MuiTextField
93
- });
94
- module.exports = __toCommonJS(src_exports);
95
-
96
- // src/components/MuiTextField.tsx
97
- var import_TextField = __toESM(require("@mui/material/TextField"));
98
- var import_react5 = __toESM(require("react"));
99
-
100
- // src/core/validator/ValidatorComponent.jsx
101
- var import_react4 = __toESM(require("react"));
102
- var import_prop_types3 = __toESM(require("prop-types"));
103
- var import_promise_polyfill2 = __toESM(require("promise-polyfill"));
104
- var import_react_lifecycles_compat = require("react-lifecycles-compat");
105
-
106
- // src/core/validator/ValidatorForm.jsx
107
- var import_react3 = __toESM(require("react"));
108
- var import_prop_types2 = __toESM(require("prop-types"));
109
- var import_promise_polyfill = __toESM(require("promise-polyfill"));
110
-
111
- // src/core/context/index.ts
112
- var import_react2 = __toESM(require("react"));
113
-
114
- // src/core/context/implementation.js
115
- var import_react = __toESM(require("react"));
116
- var import_prop_types = __toESM(require("prop-types"));
117
- var import_warning = __toESM(require("warning"));
118
- var MAX_SIGNED_31_BIT_INT = 1073741823;
119
- var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
120
- function getUniqueId() {
121
- const key = "__global_unique_id__";
122
- return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1;
123
- }
124
- function objectIs(x, y) {
125
- if (x === y) {
126
- return x !== 0 || 1 / x === 1 / y;
127
- } else {
128
- return x !== x && y !== y;
129
- }
130
- }
131
- function createEventEmitter(value) {
132
- let handlers = [];
133
- return {
134
- on(handler) {
135
- handlers.push(handler);
136
- },
137
- off(handler) {
138
- handlers = handlers.filter((h) => h !== handler);
139
- },
140
- get() {
141
- return value;
142
- },
143
- set(newValue, changedBits) {
144
- value = newValue;
145
- handlers.forEach((handler) => handler(value, changedBits));
146
- }
147
- };
148
- }
149
- function onlyChild(children) {
150
- return Array.isArray(children) ? children[0] : children;
151
- }
152
- function createReactContext(defaultValue, calculateChangedBits) {
153
- const contextProp = "__create-react-context-" + getUniqueId() + "__";
154
- class Provider extends import_react.Component {
155
- emitter = createEventEmitter(this.props.value);
156
- static childContextTypes = {
157
- [contextProp]: import_prop_types.default.object.isRequired
158
- };
159
- getChildContext() {
160
- return {
161
- [contextProp]: this.emitter
162
- };
163
- }
164
- static getDerivedStateFromProps(props, state) {
165
- if (props.value !== nextProps.value) {
166
- let oldValue = props.value;
167
- let newValue = nextProps.value;
168
- let changedBits;
169
- if (objectIs(oldValue, newValue)) {
170
- changedBits = 0;
171
- } else {
172
- changedBits = typeof calculateChangedBits === "function" ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
173
- if (process.env.NODE_ENV !== "production") {
174
- (0, import_warning.default)(
175
- (changedBits & MAX_SIGNED_31_BIT_INT) === changedBits,
176
- "calculateChangedBits: Expected the return value to be a 31-bit integer. Instead received: %s",
177
- changedBits
178
- );
179
- }
180
- changedBits |= 0;
181
- if (changedBits !== 0) {
182
- this.emitter.set(nextProps.value, changedBits);
183
- }
184
- }
185
- }
186
- return null;
187
- }
188
- render() {
189
- return this.props.children;
190
- }
191
- }
192
- class Consumer extends import_react.Component {
193
- static contextTypes = {
194
- [contextProp]: import_prop_types.default.object
195
- };
196
- observedBits;
197
- state = {
198
- value: this.getValue()
199
- };
200
- static getDerivedStateFromProps(props, state) {
201
- let { observedBits } = nextProps;
202
- this.observedBits = observedBits === void 0 || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;
203
- return null;
204
- }
205
- componentDidMount() {
206
- if (this.context[contextProp]) {
207
- this.context[contextProp].on(this.onUpdate);
208
- }
209
- let { observedBits } = this.props;
210
- this.observedBits = observedBits === void 0 || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;
211
- }
212
- componentWillUnmount() {
213
- if (this.context[contextProp]) {
214
- this.context[contextProp].off(this.onUpdate);
215
- }
216
- }
217
- getValue() {
218
- if (this.context[contextProp]) {
219
- return this.context[contextProp].get();
220
- } else {
221
- return defaultValue;
222
- }
223
- }
224
- onUpdate = (newValue, changedBits) => {
225
- const observedBits = this.observedBits | 0;
226
- if ((observedBits & changedBits) !== 0) {
227
- this.setState({ value: this.getValue() });
228
- }
229
- };
230
- render() {
231
- return onlyChild(this.props.children)(this.state.value);
232
- }
233
- }
234
- return {
235
- Provider,
236
- Consumer
237
- };
238
- }
239
- var implementation_default = createReactContext;
240
-
241
- // src/core/context/index.ts
242
- var context_default = import_react2.default.createContext || implementation_default;
243
-
244
- // src/core/validator/ValidatorForm.jsx
245
- var import_ValidationRules = __toESM(require_ValidationRules());
246
- var FormContext = context_default("form");
247
- var ValidatorForm = class extends import_react3.default.Component {
248
- static getValidator = (validator, value, includeRequired) => {
249
- let result = true;
250
- let name = validator;
251
- if (name !== "required" || includeRequired) {
252
- let extra;
253
- const splitIdx = validator.indexOf(":");
254
- if (splitIdx !== -1) {
255
- name = validator.substring(0, splitIdx);
256
- extra = validator.substring(splitIdx + 1);
257
- }
258
- result = import_ValidationRules.default[name](value, extra);
259
- }
260
- return result;
261
- };
262
- getFormHelpers = () => ({
263
- form: {
264
- attachToForm: this.attachToForm,
265
- detachFromForm: this.detachFromForm,
266
- instantValidate: this.instantValidate,
267
- debounceTime: this.debounceTime
268
- }
269
- });
270
- instantValidate = this.props.instantValidate !== void 0 ? this.props.instantValidate : true;
271
- debounceTime = this.props.debounceTime;
272
- childs = [];
273
- errors = [];
274
- attachToForm = (component) => {
275
- if (this.childs.indexOf(component) === -1) {
276
- this.childs.push(component);
277
- }
278
- };
279
- detachFromForm = (component) => {
280
- const componentPos = this.childs.indexOf(component);
281
- if (componentPos !== -1) {
282
- this.childs = this.childs.slice(0, componentPos).concat(this.childs.slice(componentPos + 1));
283
- }
284
- };
285
- submit = (event) => {
286
- if (event) {
287
- event.preventDefault();
288
- event.persist();
289
- }
290
- this.errors = [];
291
- this.walk(this.childs).then((result) => {
292
- if (this.errors.length) {
293
- this.props.onError(this.errors);
294
- }
295
- if (result) {
296
- this.props.onSubmit(event);
297
- }
298
- return result;
299
- });
300
- };
301
- walk = (children, dryRun) => {
302
- const self = this;
303
- return new import_promise_polyfill.default((resolve) => {
304
- let result = true;
305
- if (Array.isArray(children)) {
306
- import_promise_polyfill.default.all(
307
- children.map((input) => self.checkInput(input, dryRun))
308
- ).then((data) => {
309
- data.forEach((item) => {
310
- if (!item) {
311
- result = false;
312
- }
313
- });
314
- resolve(result);
315
- });
316
- } else {
317
- self.walk([children], dryRun).then((result2) => resolve(result2));
318
- }
319
- });
320
- };
321
- checkInput = (input, dryRun) => new import_promise_polyfill.default((resolve) => {
322
- let result = true;
323
- const validators = input.props.validators;
324
- if (validators) {
325
- this.validate(input, true, dryRun).then((data) => {
326
- if (!data) {
327
- result = false;
328
- }
329
- resolve(result);
330
- });
331
- } else {
332
- resolve(result);
333
- }
334
- });
335
- validate = (input, includeRequired, dryRun) => new import_promise_polyfill.default((resolve) => {
336
- const { value } = input.props;
337
- input.validate(value, includeRequired, dryRun).then((valid) => {
338
- if (!valid) {
339
- this.errors.push(input);
340
- }
341
- resolve(valid);
342
- });
343
- });
344
- find = (collection, fn) => {
345
- for (let i = 0, l = collection.length; i < l; i++) {
346
- const item = collection[i];
347
- if (fn(item)) {
348
- return item;
349
- }
350
- }
351
- return null;
352
- };
353
- resetValidations = () => {
354
- this.childs.forEach((child) => {
355
- child.validateDebounced.cancel();
356
- child.setState({ isValid: true });
357
- });
358
- };
359
- isFormValid = (dryRun = true) => this.walk(this.childs, dryRun);
360
- render() {
361
- const {
362
- onSubmit,
363
- instantValidate,
364
- onError,
365
- debounceTime,
366
- children,
367
- ...rest
368
- } = this.props;
369
- return /* @__PURE__ */ import_react3.default.createElement(FormContext.Provider, { value: this.getFormHelpers() }, /* @__PURE__ */ import_react3.default.createElement("form", { ...rest, onSubmit: this.submit }, children));
370
- }
371
- };
372
- ValidatorForm.addValidationRule = (name, callback) => {
373
- import_ValidationRules.default[name] = callback;
374
- };
375
- ValidatorForm.getValidationRule = (name) => import_ValidationRules.default[name];
376
- ValidatorForm.hasValidationRule = (name) => import_ValidationRules.default[name] && typeof import_ValidationRules.default[name] === "function";
377
- ValidatorForm.removeValidationRule = (name) => {
378
- delete import_ValidationRules.default[name];
379
- };
380
- ValidatorForm.propTypes = {
381
- onSubmit: import_prop_types2.default.func.isRequired,
382
- instantValidate: import_prop_types2.default.bool,
383
- children: import_prop_types2.default.node,
384
- onError: import_prop_types2.default.func,
385
- debounceTime: import_prop_types2.default.number
386
- };
387
- ValidatorForm.defaultProps = {
388
- onError: () => {
389
- },
390
- debounceTime: 0
391
- };
392
- var ValidatorForm_default = ValidatorForm;
393
-
394
- // src/core/utils/utils.ts
395
- var debounce = (func, wait, immediate) => {
396
- let timeout;
397
- function cancel() {
398
- if (timeout !== void 0) {
399
- clearTimeout(timeout);
400
- }
401
- }
402
- const debounced = function debounced2(...args) {
403
- const context = args;
404
- const later = function delayed() {
405
- timeout = null;
406
- if (!immediate) {
407
- func.apply(context, args);
408
- }
409
- };
410
- const callNow = immediate && !timeout;
411
- clearTimeout(timeout);
412
- timeout = setTimeout(later, wait);
413
- if (callNow) {
414
- func.apply(context, args);
415
- }
416
- };
417
- debounced.cancel = cancel;
418
- return debounced;
419
- };
420
-
421
- // src/core/validator/ValidatorComponent.jsx
422
- var ValidatorComponent = class extends import_react4.default.Component {
423
- static getDerivedStateFromProps(nextProps2, prevState) {
424
- if (nextProps2.validators && nextProps2.errorMessages && (prevState.validators !== nextProps2.validators || prevState.errorMessages !== nextProps2.errorMessages)) {
425
- return {
426
- value: nextProps2.value,
427
- validators: nextProps2.validators,
428
- errorMessages: nextProps2.errorMessages
429
- };
430
- }
431
- return {
432
- value: nextProps2.value
433
- };
434
- }
435
- state = {
436
- isValid: true,
437
- value: this.props.value,
438
- errorMessages: this.props.errorMessages,
439
- validators: this.props.validators
440
- };
441
- componentDidMount() {
442
- this.configure();
443
- }
444
- shouldComponentUpdate(nextProps2, nextState) {
445
- return this.state !== nextState || this.props !== nextProps2;
446
- }
447
- componentDidUpdate(prevProps, prevState) {
448
- if (this.instantValidate && this.props.value !== prevState.value) {
449
- this.validateDebounced(this.props.value, this.props.withRequiredValidator);
450
- }
451
- }
452
- componentWillUnmount() {
453
- this.form.detachFromForm(this);
454
- this.validateDebounced.cancel();
455
- }
456
- getErrorMessage = () => {
457
- const { errorMessages } = this.state;
458
- const type = typeof errorMessages;
459
- if (type === "string") {
460
- return errorMessages;
461
- } else if (type === "object") {
462
- if (this.invalid.length > 0) {
463
- return errorMessages[this.invalid[0]];
464
- }
465
- }
466
- console.log("unknown errorMessages type", errorMessages);
467
- return true;
468
- };
469
- instantValidate = true;
470
- invalid = [];
471
- configure = () => {
472
- this.form.attachToForm(this);
473
- this.instantValidate = this.form.instantValidate;
474
- this.debounceTime = this.form.debounceTime;
475
- this.validateDebounced = debounce(this.validate, this.debounceTime);
476
- };
477
- validate = (value, includeRequired = false, dryRun = false) => {
478
- const validations = import_promise_polyfill2.default.all(
479
- this.state.validators.map((validator) => ValidatorForm_default.getValidator(validator, value, includeRequired))
480
- );
481
- return validations.then((results) => {
482
- this.invalid = [];
483
- let valid = true;
484
- results.forEach((result, key) => {
485
- if (!result) {
486
- valid = false;
487
- this.invalid.push(key);
488
- }
489
- });
490
- if (!dryRun) {
491
- this.setState({ isValid: valid }, () => {
492
- this.props.validatorListener(this.state.isValid);
493
- });
494
- }
495
- return valid;
496
- });
497
- };
498
- isValid = () => this.state.isValid;
499
- makeInvalid = () => {
500
- this.setState({ isValid: false });
501
- };
502
- makeValid = () => {
503
- this.setState({ isValid: true });
504
- };
505
- renderComponent = (form) => {
506
- if (!this.form) {
507
- this.form = form;
508
- }
509
- return this.renderValidatorComponent();
510
- };
511
- render() {
512
- return /* @__PURE__ */ import_react4.default.createElement(FormContext.Consumer, null, ({ form }) => /* @__PURE__ */ import_react4.default.createElement("div", { ...this.props.containerProps }, this.renderComponent(form)));
513
- }
514
- };
515
- ValidatorComponent.propTypes = {
516
- errorMessages: import_prop_types3.default.oneOfType([
517
- import_prop_types3.default.array,
518
- import_prop_types3.default.string
519
- ]),
520
- validators: import_prop_types3.default.array,
521
- value: import_prop_types3.default.any,
522
- validatorListener: import_prop_types3.default.func,
523
- withRequiredValidator: import_prop_types3.default.bool,
524
- containerProps: import_prop_types3.default.object
525
- };
526
- ValidatorComponent.defaultProps = {
527
- errorMessages: "error",
528
- validators: [],
529
- validatorListener: () => {
530
- }
531
- };
532
- (0, import_react_lifecycles_compat.polyfill)(ValidatorComponent);
533
- var ValidatorComponent_default = ValidatorComponent;
534
-
535
- // src/components/MuiTextField.tsx
536
- var TextValidator = class extends ValidatorComponent_default {
537
- renderValidatorComponent() {
538
- const {
539
- error,
540
- errorMessages,
541
- validators,
542
- requiredError,
543
- helperText,
544
- validatorListener,
545
- withRequiredValidator,
546
- containerProps,
547
- ...rest
548
- } = this.props;
549
- const { isValid } = this.state;
550
- return /* @__PURE__ */ import_react5.default.createElement(
551
- import_TextField.default,
552
- {
553
- ...rest,
554
- error: !isValid || error,
555
- helperText: !isValid && this.getErrorMessage() || helperText
556
- }
557
- );
558
- }
559
- };
560
-
561
- // src/components/MuiSelect.tsx
562
- var import_material = require("@mui/material");
563
- var import_react6 = __toESM(require("react"));
564
- var MuiSelect = class extends ValidatorComponent_default {
565
- renderValidatorComponent() {
566
- const {
567
- error,
568
- errorMessages,
569
- validators,
570
- requiredError,
571
- helperText,
572
- validatorListener,
573
- withRequiredValidator,
574
- containerProps,
575
- ...rest
576
- } = this.props;
577
- const { isValid } = this.state;
578
- return /* @__PURE__ */ import_react6.default.createElement(
579
- import_material.TextField,
580
- {
581
- ...rest,
582
- select: true,
583
- error: !isValid || error,
584
- helperText: !isValid && this.getErrorMessage() || helperText
585
- }
586
- );
587
- }
588
- };
589
-
590
- // src/index.ts
591
- var MuiTextField = TextValidator;
592
- var MuiSelect2 = MuiSelect;
593
- var MuiComponent = ValidatorComponent_default;
594
- var MuiForm = ValidatorForm_default;
595
- // Annotate the CommonJS export names for ESM import in node:
596
- 0 && (module.exports = {
597
- MuiComponent,
598
- MuiForm,
599
- MuiSelect,
600
- MuiTextField
601
- });