react-mui-form-validator 1.1.3 → 1.1.7

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/lib/index.d.ts ADDED
@@ -0,0 +1,122 @@
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/lib/index.js ADDED
@@ -0,0 +1,598 @@
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_react_lifecycles_compat = require("react-lifecycles-compat");
104
+
105
+ // src/core/validator/ValidatorForm.jsx
106
+ var import_react3 = __toESM(require("react"));
107
+ var import_prop_types2 = __toESM(require("prop-types"));
108
+
109
+ // src/core/context/index.ts
110
+ var import_react2 = __toESM(require("react"));
111
+
112
+ // src/core/context/implementation.js
113
+ var import_react = __toESM(require("react"));
114
+ var import_prop_types = __toESM(require("prop-types"));
115
+ var import_warning = __toESM(require("warning"));
116
+ var MAX_SIGNED_31_BIT_INT = 1073741823;
117
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
118
+ function getUniqueId() {
119
+ const key = "__global_unique_id__";
120
+ return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1;
121
+ }
122
+ function objectIs(x, y) {
123
+ if (x === y) {
124
+ return x !== 0 || 1 / x === 1 / y;
125
+ } else {
126
+ return x !== x && y !== y;
127
+ }
128
+ }
129
+ function createEventEmitter(value) {
130
+ let handlers = [];
131
+ return {
132
+ on(handler) {
133
+ handlers.push(handler);
134
+ },
135
+ off(handler) {
136
+ handlers = handlers.filter((h) => h !== handler);
137
+ },
138
+ get() {
139
+ return value;
140
+ },
141
+ set(newValue, changedBits) {
142
+ value = newValue;
143
+ handlers.forEach((handler) => handler(value, changedBits));
144
+ }
145
+ };
146
+ }
147
+ function onlyChild(children) {
148
+ return Array.isArray(children) ? children[0] : children;
149
+ }
150
+ function createReactContext(defaultValue, calculateChangedBits) {
151
+ const contextProp = "__create-react-context-" + getUniqueId() + "__";
152
+ class Provider extends import_react.Component {
153
+ emitter = createEventEmitter(this.props.value);
154
+ static childContextTypes = {
155
+ [contextProp]: import_prop_types.default.object.isRequired
156
+ };
157
+ getChildContext() {
158
+ return {
159
+ [contextProp]: this.emitter
160
+ };
161
+ }
162
+ static getDerivedStateFromProps(props, state) {
163
+ if (props.value !== nextProps.value) {
164
+ let oldValue = props.value;
165
+ let newValue = nextProps.value;
166
+ let changedBits;
167
+ if (objectIs(oldValue, newValue)) {
168
+ changedBits = 0;
169
+ } else {
170
+ changedBits = typeof calculateChangedBits === "function" ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
171
+ if (process.env.NODE_ENV !== "production") {
172
+ (0, import_warning.default)(
173
+ (changedBits & MAX_SIGNED_31_BIT_INT) === changedBits,
174
+ "calculateChangedBits: Expected the return value to be a 31-bit integer. Instead received: %s",
175
+ changedBits
176
+ );
177
+ }
178
+ changedBits |= 0;
179
+ if (changedBits !== 0) {
180
+ this.emitter.set(nextProps.value, changedBits);
181
+ }
182
+ }
183
+ }
184
+ return null;
185
+ }
186
+ render() {
187
+ return this.props.children;
188
+ }
189
+ }
190
+ class Consumer extends import_react.Component {
191
+ static contextTypes = {
192
+ [contextProp]: import_prop_types.default.object
193
+ };
194
+ observedBits;
195
+ state = {
196
+ value: this.getValue()
197
+ };
198
+ static getDerivedStateFromProps(props, state) {
199
+ let { observedBits } = nextProps;
200
+ this.observedBits = observedBits === void 0 || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;
201
+ return null;
202
+ }
203
+ componentDidMount() {
204
+ if (this.context[contextProp]) {
205
+ this.context[contextProp].on(this.onUpdate);
206
+ }
207
+ let { observedBits } = this.props;
208
+ this.observedBits = observedBits === void 0 || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;
209
+ }
210
+ componentWillUnmount() {
211
+ if (this.context[contextProp]) {
212
+ this.context[contextProp].off(this.onUpdate);
213
+ }
214
+ }
215
+ getValue() {
216
+ if (this.context[contextProp]) {
217
+ return this.context[contextProp].get();
218
+ } else {
219
+ return defaultValue;
220
+ }
221
+ }
222
+ onUpdate = (newValue, changedBits) => {
223
+ const observedBits = this.observedBits | 0;
224
+ if ((observedBits & changedBits) !== 0) {
225
+ this.setState({ value: this.getValue() });
226
+ }
227
+ };
228
+ render() {
229
+ return onlyChild(this.props.children)(this.state.value);
230
+ }
231
+ }
232
+ return {
233
+ Provider,
234
+ Consumer
235
+ };
236
+ }
237
+ var implementation_default = createReactContext;
238
+
239
+ // src/core/context/index.ts
240
+ var context_default = import_react2.default.createContext || implementation_default;
241
+
242
+ // src/core/validator/ValidatorForm.jsx
243
+ var import_ValidationRules = __toESM(require_ValidationRules());
244
+ var FormContext = context_default("form");
245
+ var ValidatorForm = class extends import_react3.default.Component {
246
+ static getValidator = (validator, value, includeRequired) => {
247
+ let result = true;
248
+ let name = validator;
249
+ if (name !== "required" || includeRequired) {
250
+ let extra;
251
+ const splitIdx = validator.indexOf(":");
252
+ if (splitIdx !== -1) {
253
+ name = validator.substring(0, splitIdx);
254
+ extra = validator.substring(splitIdx + 1);
255
+ }
256
+ result = import_ValidationRules.default[name](value, extra);
257
+ }
258
+ return result;
259
+ };
260
+ getFormHelpers = () => ({
261
+ form: {
262
+ attachToForm: this.attachToForm,
263
+ detachFromForm: this.detachFromForm,
264
+ instantValidate: this.instantValidate,
265
+ debounceTime: this.debounceTime
266
+ }
267
+ });
268
+ instantValidate = this.props.instantValidate !== void 0 ? this.props.instantValidate : true;
269
+ debounceTime = this.props.debounceTime;
270
+ childs = [];
271
+ errors = [];
272
+ attachToForm = (component) => {
273
+ if (this.childs.indexOf(component) === -1) {
274
+ this.childs.push(component);
275
+ }
276
+ };
277
+ detachFromForm = (component) => {
278
+ const componentPos = this.childs.indexOf(component);
279
+ if (componentPos !== -1) {
280
+ this.childs = this.childs.slice(0, componentPos).concat(this.childs.slice(componentPos + 1));
281
+ }
282
+ };
283
+ submit = (event) => {
284
+ if (event) {
285
+ event.preventDefault();
286
+ event.persist();
287
+ }
288
+ this.errors = [];
289
+ this.walk(this.childs).then((result) => {
290
+ if (this.errors.length) {
291
+ this.props.onError(this.errors);
292
+ }
293
+ if (result) {
294
+ this.props.onSubmit(event);
295
+ }
296
+ return result;
297
+ });
298
+ };
299
+ walk = (children, dryRun) => {
300
+ const self = this;
301
+ return new Promise((resolve) => {
302
+ let result = true;
303
+ if (Array.isArray(children)) {
304
+ Promise.all(
305
+ children.map((input) => self.checkInput(input, dryRun))
306
+ ).then((data) => {
307
+ data.forEach((item) => {
308
+ if (!item) {
309
+ result = false;
310
+ }
311
+ });
312
+ resolve(result);
313
+ });
314
+ } else {
315
+ self.walk([children], dryRun).then((result2) => resolve(result2));
316
+ }
317
+ });
318
+ };
319
+ checkInput = (input, dryRun) => new Promise((resolve) => {
320
+ let result = true;
321
+ const validators = input.props.validators;
322
+ if (validators) {
323
+ this.validate(input, true, dryRun).then((data) => {
324
+ if (!data) {
325
+ result = false;
326
+ }
327
+ resolve(result);
328
+ });
329
+ } else {
330
+ resolve(result);
331
+ }
332
+ });
333
+ validate = (input, includeRequired, dryRun) => new Promise((resolve) => {
334
+ const { value } = input.props;
335
+ input.validate(value, includeRequired, dryRun).then((valid) => {
336
+ if (!valid) {
337
+ this.errors.push(input);
338
+ }
339
+ resolve(valid);
340
+ });
341
+ });
342
+ find = (collection, fn) => {
343
+ for (let i = 0, l = collection.length; i < l; i++) {
344
+ const item = collection[i];
345
+ if (fn(item)) {
346
+ return item;
347
+ }
348
+ }
349
+ return null;
350
+ };
351
+ resetValidations = () => {
352
+ this.childs.forEach((child) => {
353
+ child.validateDebounced.cancel();
354
+ child.setState({ isValid: true });
355
+ });
356
+ };
357
+ isFormValid = (dryRun = true) => this.walk(this.childs, dryRun);
358
+ render() {
359
+ const {
360
+ onSubmit,
361
+ instantValidate,
362
+ onError,
363
+ debounceTime,
364
+ children,
365
+ ...rest
366
+ } = this.props;
367
+ return /* @__PURE__ */ import_react3.default.createElement(FormContext.Provider, { value: this.getFormHelpers() }, /* @__PURE__ */ import_react3.default.createElement("form", { ...rest, onSubmit: this.submit }, children));
368
+ }
369
+ };
370
+ ValidatorForm.addValidationRule = (name, callback) => {
371
+ import_ValidationRules.default[name] = callback;
372
+ };
373
+ ValidatorForm.getValidationRule = (name) => import_ValidationRules.default[name];
374
+ ValidatorForm.hasValidationRule = (name) => import_ValidationRules.default[name] && typeof import_ValidationRules.default[name] === "function";
375
+ ValidatorForm.removeValidationRule = (name) => {
376
+ delete import_ValidationRules.default[name];
377
+ };
378
+ ValidatorForm.propTypes = {
379
+ onSubmit: import_prop_types2.default.func.isRequired,
380
+ instantValidate: import_prop_types2.default.bool,
381
+ children: import_prop_types2.default.node,
382
+ onError: import_prop_types2.default.func,
383
+ debounceTime: import_prop_types2.default.number
384
+ };
385
+ ValidatorForm.defaultProps = {
386
+ onError: () => {
387
+ },
388
+ debounceTime: 0
389
+ };
390
+ var ValidatorForm_default = ValidatorForm;
391
+
392
+ // src/core/utils/utils.ts
393
+ var debounce = (func, wait, immediate) => {
394
+ let timeout;
395
+ function cancel() {
396
+ if (timeout !== void 0) {
397
+ clearTimeout(timeout);
398
+ }
399
+ }
400
+ const debounced = function debounced2(...args) {
401
+ const context = args;
402
+ const later = function delayed() {
403
+ timeout = null;
404
+ if (!immediate) {
405
+ func.apply(context, args);
406
+ }
407
+ };
408
+ const callNow = immediate && !timeout;
409
+ clearTimeout(timeout);
410
+ timeout = setTimeout(later, wait);
411
+ if (callNow) {
412
+ func.apply(context, args);
413
+ }
414
+ };
415
+ debounced.cancel = cancel;
416
+ return debounced;
417
+ };
418
+
419
+ // src/core/validator/ValidatorComponent.jsx
420
+ var ValidatorComponent = class extends import_react4.default.Component {
421
+ static getDerivedStateFromProps(nextProps2, prevState) {
422
+ if (nextProps2.validators && nextProps2.errorMessages && (prevState.validators !== nextProps2.validators || prevState.errorMessages !== nextProps2.errorMessages)) {
423
+ return {
424
+ value: nextProps2.value,
425
+ validators: nextProps2.validators,
426
+ errorMessages: nextProps2.errorMessages
427
+ };
428
+ }
429
+ return {
430
+ value: nextProps2.value
431
+ };
432
+ }
433
+ state = {
434
+ isValid: true,
435
+ value: this.props.value,
436
+ errorMessages: this.props.errorMessages,
437
+ validators: this.props.validators
438
+ };
439
+ componentDidMount() {
440
+ this.configure();
441
+ }
442
+ shouldComponentUpdate(nextProps2, nextState) {
443
+ return this.state !== nextState || this.props !== nextProps2;
444
+ }
445
+ componentDidUpdate(prevProps, prevState) {
446
+ if (this.instantValidate && this.props.value !== prevState.value) {
447
+ this.validateDebounced(this.props.value, this.props.withRequiredValidator);
448
+ }
449
+ }
450
+ componentWillUnmount() {
451
+ this.form.detachFromForm(this);
452
+ this.validateDebounced.cancel();
453
+ }
454
+ getErrorMessage = () => {
455
+ const { errorMessages } = this.state;
456
+ const type = typeof errorMessages;
457
+ if (type === "string") {
458
+ return errorMessages;
459
+ } else if (type === "object") {
460
+ if (this.invalid.length > 0) {
461
+ return errorMessages[this.invalid[0]];
462
+ }
463
+ }
464
+ console.log("unknown errorMessages type", errorMessages);
465
+ return true;
466
+ };
467
+ instantValidate = true;
468
+ invalid = [];
469
+ configure = () => {
470
+ this.form.attachToForm(this);
471
+ this.instantValidate = this.form.instantValidate;
472
+ this.debounceTime = this.form.debounceTime;
473
+ this.validateDebounced = debounce(this.validate, this.debounceTime);
474
+ };
475
+ validate = async (value, includeRequired = false, dryRun = false) => {
476
+ const validations = Promise.all(
477
+ this.state.validators.map((validator) => ValidatorForm_default.getValidator(validator, value, includeRequired))
478
+ );
479
+ const results = await validations;
480
+ this.invalid = [];
481
+ let valid = true;
482
+ results.forEach((result, key) => {
483
+ if (!result) {
484
+ valid = false;
485
+ this.invalid.push(key);
486
+ }
487
+ });
488
+ if (!dryRun) {
489
+ this.setState({ isValid: valid }, () => {
490
+ this.props.validatorListener(this.state.isValid);
491
+ });
492
+ }
493
+ return valid;
494
+ };
495
+ isValid = () => this.state.isValid;
496
+ makeInvalid = () => {
497
+ this.setState({ isValid: false });
498
+ };
499
+ makeValid = () => {
500
+ this.setState({ isValid: true });
501
+ };
502
+ renderComponent = (form) => {
503
+ if (!this.form) {
504
+ this.form = form;
505
+ }
506
+ return this.renderValidatorComponent();
507
+ };
508
+ render() {
509
+ return /* @__PURE__ */ import_react4.default.createElement(FormContext.Consumer, null, ({ form }) => /* @__PURE__ */ import_react4.default.createElement("div", { ...this.props.containerProps }, this.renderComponent(form)));
510
+ }
511
+ };
512
+ ValidatorComponent.propTypes = {
513
+ errorMessages: import_prop_types3.default.oneOfType([
514
+ import_prop_types3.default.array,
515
+ import_prop_types3.default.string
516
+ ]),
517
+ validators: import_prop_types3.default.array,
518
+ value: import_prop_types3.default.any,
519
+ validatorListener: import_prop_types3.default.func,
520
+ withRequiredValidator: import_prop_types3.default.bool,
521
+ containerProps: import_prop_types3.default.object
522
+ };
523
+ ValidatorComponent.defaultProps = {
524
+ errorMessages: "error",
525
+ validators: [],
526
+ validatorListener: () => {
527
+ }
528
+ };
529
+ (0, import_react_lifecycles_compat.polyfill)(ValidatorComponent);
530
+ var ValidatorComponent_default = ValidatorComponent;
531
+
532
+ // src/components/MuiTextField.tsx
533
+ var TextValidator = class extends ValidatorComponent_default {
534
+ renderValidatorComponent() {
535
+ const {
536
+ error,
537
+ errorMessages,
538
+ validators,
539
+ requiredError,
540
+ helperText,
541
+ validatorListener,
542
+ withRequiredValidator,
543
+ containerProps,
544
+ ...rest
545
+ } = this.props;
546
+ const { isValid } = this.state;
547
+ return /* @__PURE__ */ import_react5.default.createElement(
548
+ import_TextField.default,
549
+ {
550
+ ...rest,
551
+ error: !isValid || error,
552
+ helperText: !isValid && this.getErrorMessage() || helperText
553
+ }
554
+ );
555
+ }
556
+ };
557
+
558
+ // src/components/MuiSelect.tsx
559
+ var import_material = require("@mui/material");
560
+ var import_react6 = __toESM(require("react"));
561
+ var MuiSelect = class extends ValidatorComponent_default {
562
+ renderValidatorComponent() {
563
+ const {
564
+ error,
565
+ errorMessages,
566
+ validators,
567
+ requiredError,
568
+ helperText,
569
+ validatorListener,
570
+ withRequiredValidator,
571
+ containerProps,
572
+ ...rest
573
+ } = this.props;
574
+ const { isValid } = this.state;
575
+ return /* @__PURE__ */ import_react6.default.createElement(
576
+ import_material.TextField,
577
+ {
578
+ ...rest,
579
+ select: true,
580
+ error: !isValid || error,
581
+ helperText: !isValid && this.getErrorMessage() || helperText
582
+ }
583
+ );
584
+ }
585
+ };
586
+
587
+ // src/index.ts
588
+ var MuiTextField = TextValidator;
589
+ var MuiSelect2 = MuiSelect;
590
+ var MuiComponent = ValidatorComponent_default;
591
+ var MuiForm = ValidatorForm_default;
592
+ // Annotate the CommonJS export names for ESM import in node:
593
+ 0 && (module.exports = {
594
+ MuiComponent,
595
+ MuiForm,
596
+ MuiSelect,
597
+ MuiTextField
598
+ });
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "react-mui-form-validator",
3
- "version": "1.1.3",
3
+ "version": "1.1.7",
4
4
  "description": "Validator for forms designed with material-ui components.",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
7
  "scripts": {
8
- "build": "tsup src/index.ts --dts"
8
+ "build": "tsup src/index.ts --dts --outDir=lib"
9
9
  },
10
10
  "repository": {
11
11
  "type": "git",
@@ -26,14 +26,12 @@
26
26
  },
27
27
  "homepage": "https://github.com/Blencm/react-mui-form-validator#readme",
28
28
  "dependencies": {
29
- "@mui/material": "^5.13.6",
29
+ "@mui/material": "^5.14.1",
30
30
  "@types/prop-types": "^15.7.5",
31
31
  "prop-types": "^15.8.1",
32
32
  "react": "^18.2.0",
33
33
  "react-dom": "^18.2.0",
34
34
  "react-lifecycles-compat": "^3.0.4",
35
- "tsup": "^7.1.0",
36
- "typescript": "^5.1.6",
37
35
  "warning": "^4.0.3"
38
36
  },
39
37
  "peerDependencies": {
@@ -41,20 +39,22 @@
41
39
  "react-dom": "^17.0.0 || ^18.2.0 || ^19.0.0 || ^20.0.0"
42
40
  },
43
41
  "devDependencies": {
44
- "@types/node": "^20.3.3",
45
- "@types/react": "18.2.14",
46
- "@types/react-dom": "^18.2.6",
42
+ "@types/node": "^20.4.4",
43
+ "@types/react": "18.2.16",
44
+ "@types/react-dom": "^18.2.7",
47
45
  "@types/react-lifecycles-compat": "^3.0.1",
48
- "@typescript-eslint/eslint-plugin": "5.60.1",
49
- "@typescript-eslint/parser": "5.60.1",
50
- "eslint": "^8.44.0",
46
+ "@typescript-eslint/eslint-plugin": "^6.2.0",
47
+ "@typescript-eslint/parser": "^6.2.0",
48
+ "eslint": "^8.45.0",
49
+ "tsup": "^7.1.0",
51
50
  "eslint-config-airbnb": "^19.0.4",
52
- "eslint-config-airbnb-typescript": "17.0.0",
53
- "eslint-config-prettier": "8.8.0",
51
+ "eslint-config-airbnb-typescript": "^17.1.0",
52
+ "eslint-config-prettier": "^8.8.0",
54
53
  "eslint-plugin-import": "^2.27.5",
55
54
  "eslint-plugin-jsx-a11y": "^6.7.1",
56
- "eslint-plugin-prettier": "4.2.1",
57
- "eslint-plugin-react": "^7.32.2",
58
- "eslint-plugin-react-hooks": "^4.6.0"
55
+ "eslint-plugin-prettier": "^5.0.0",
56
+ "eslint-plugin-react": "^7.33.0",
57
+ "eslint-plugin-react-hooks": "^4.6.0",
58
+ "typescript": "^5.1.6"
59
59
  }
60
60
  }
package/tsconfig.json CHANGED
@@ -13,7 +13,7 @@
13
13
  "allowSyntheticDefaultImports": true,
14
14
  "noFallthroughCasesInSwitch": true,
15
15
 
16
- "outDir": "dist",
16
+ "outDir": "lib",
17
17
  "declaration": true,
18
18
  "moduleResolution": "node",
19
19
  "resolveJsonModule": true,